package org.ezplatform.office.meeting.info.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.ezplatform.cloud.api.component.attachment.AttachmentUtilsService;
import org.ezplatform.cloud.api.component.popuser.PopUserScopeUtilService;
import org.ezplatform.cloud.api.system.org.OrgApiService;
import org.ezplatform.cloud.api.system.user.UserApiService;
import org.ezplatform.cloud.common.client.RestClient;
import org.ezplatform.cloud.common.util.JwtUtils;
import org.ezplatform.component.permission.service.CmpPermissionService;
import org.ezplatform.component.popuser.service.CmpPopUserOrgName;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.office.group.service.PersonalGroupUserService;
import org.ezplatform.office.meeting.common.util.MeetingSendMsgUtils;
import org.ezplatform.office.meeting.common.util.MeetingUtils;
import org.ezplatform.office.meeting.common.util.SendMsgThread;
import org.ezplatform.office.meeting.info.dao.ApplyRecordDao;
import org.ezplatform.office.meeting.info.entity.ApplyRecord;
import org.ezplatform.office.meeting.info.entity.MeetingScope;
import org.ezplatform.office.meeting.info.web.rest.ApplyRecordWebApiController;
import org.ezplatform.office.meeting.notice.entity.NoticeInfo;
import org.ezplatform.office.meeting.notice.service.NoticeInfoService;
import org.ezplatform.office.meeting.setting.boardroom.entity.BoardroomSet;
import org.ezplatform.office.meeting.setting.boardroom.service.BoardroomSetService;
import org.ezplatform.office.meeting.setting.category.dao.BoardroomCategorySetDao;
import org.ezplatform.office.meeting.setting.category.entity.BoardroomCategorySet;
import org.ezplatform.util.DateUtils;
import org.ezplatform.util.GlobalConstant;
import org.ezplatform.util.JsonUtils;
import org.ezplatform.util.SqlUtils;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.UuidUtils;
import org.ezplatform.util.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("applyRecordService")
@Transactional
public class ApplyRecordService extends BaseService<ApplyRecord, String>{
    
	private final static Logger LOGGER = LoggerFactory.getLogger(ApplyRecordService.class);
	
    @Autowired
    private ApplyRecordDao dao;
    @Lazy
    @Autowired
    private BoardroomSetService boardroomSetService;
    @Lazy
    @Autowired
    private NoticeInfoService noticeInfoService;
    @Lazy
    @Autowired
    private MeetingScopeService meetingScopeService;
    @Lazy
    @Autowired
    private SignedInfoService signedInfoService;

    @Autowired
    private OrgApiService orgApiService;
    
    @Autowired
    private UserApiService userApiService;
    
    @Autowired
    private MeetingSendMsgUtils meetingSendMsgUtils;
    
    @Autowired
    private BoardroomCategorySetDao categoryDao;
	
    @Autowired
    private PopUserScopeUtilService popScopeService;
    
    @Autowired
	private AttachmentUtilsService attachmentUtilsService;
    @Lazy
    @Autowired
	private QSUserService qsUserService;
    @Lazy
    @Autowired
	private QSMeetingService qsMeetingService;
    
    @Autowired
	private PersonalGroupUserService grpUserService;
	
    @Autowired
    private CmpPopUserOrgName cmpPopUserOrgName;
    
    @Autowired
	private CmpPermissionService cmpPermissionService;
    
	@Autowired
	private RestClient restClient;
    
    @Override
    protected JpaBaseDao<ApplyRecord, String> getEntityDao() {
        return dao;
    }
    
    public List<ApplyRecord> getApplyRecordByApp(String SDate,String EDate,String boardroomId,String applyRecordId){
        return this.dao.getApplyRecordByApp(SDate,EDate,boardroomId,applyRecordId);
    }

    /**
     * 保存会议申请处理
     * @param entity
     * @return
     */
    public void saveApplyRecord(ApplyRecord entity) {
        //查询会议室管理员
        BoardroomSet  boardroomSet = this.boardroomSetService.findOne(entity.getBoardroomId());
        List<String> scopeList = new ArrayList<>();
        scopeList.add(boardroomSet.getAdminUserScope());
        
        List<MeetingScope> msList = this.meetingScopeService.getMeetingScopeList("oa_meeting_boardroom_set", "admin_user_scope", scopeList,true);
        //删除推送申请---会议室管理员
        this.noticeInfoService.deleteByApplyrecord(entity,0);
        if(msList != null){
            //推送申请---会议室管理员
            noticeInfoService.saveNoticeInfoIsApply(entity,msList);
        }
    }

    /**
     * 根据会议状态保存数据
     * @param entity
     * @param nStatus
     * @param token
     * @return
     */
    public OperationResult editSaveByStatus(ApplyRecord entity, String nStatus, String type, String token) {
    	Map failureMap = new HashMap();
        OperationResult result = null;
        entity.setStatus(Integer.valueOf(nStatus));
        //保存会议
        if(StringUtils.isNotEmpty(type)){
            entity = this.save(entity);
        }
        String applyRecordId = entity.getId();
        if("0".equals(nStatus)){//申请中
        	failureMap.put("i18NCode", "oa.meeting.meetapp");
            result = OperationResult.buildSuccessResult("申请成功",failureMap);
        }else if("1".equals(nStatus)){//未召开
            //修改会议申请通知状态
            this.noticeInfoService.deleteApproveNotice(applyRecordId);
            //发送会议审批通过通知
            this.noticeInfoService.addNoticeInfoByApplyrecord(entity,1,token);
            //新建会议签到数据
            if(entity.getIsSigned()==1){
                this.signedInfoService.addSignedInfoByApplyrecord(entity,token);
            }
            failureMap.put("i18NCode", "oa.meeting.tip43");
            result = OperationResult.buildSuccessResult("操作成功",failureMap);
        }else if("2".equals(nStatus)){//已驳回
            //修改会议申请通知状态
            this.noticeInfoService.deleteApproveNotice(applyRecordId);
            failureMap.put("i18NCode", "oa.meeting.tip44");
            result = OperationResult.buildSuccessResult("会议已驳回",failureMap);
        }else if("3".equals(nStatus)){//已取消
            //删除会议申请通知、会议通知、会议签到
            this.noticeInfoService.deleteByApplyrecord(entity);
            failureMap.put("i18NCode", "oa.meeting.meetcancel");
            result = OperationResult.buildSuccessResult("会议已取消",failureMap);
        }else if("4".equals(nStatus)){//进行中
        	failureMap.put("i18NCode", "oa.meeting.tip43");
            result = OperationResult.buildSuccessResult("操作成功",failureMap);
        }else if("5".equals(nStatus)){//已结束
        	failureMap.put("i18NCode", "oa.meeting.tip45");
            result = OperationResult.buildSuccessResult("会议已结束",failureMap);
        }
        return result;
    }
    
    /**
	 * 导出
	 * @param paramMap
	 * @return
	 */
	public List<NoticeInfo> getUserDetailListByCondition(Map<String, String> paramMap){
		
		LOGGER.debug("-----getUserDetailListByCondition----");
		
		List<NoticeInfo> noticeInfoList = new ArrayList<>();
		
		WebUser localWebUser = WebUtils.getCurrentUser();
		Map<String, Object> localHashMap = new HashMap<>();
	    localHashMap.put("applyrecordId", (String)paramMap.get("applyrecordId"));
	    LOGGER.debug("--paramMap.get(applyrecordId)-"+paramMap.get("applyrecordId"));
	    localHashMap.put("corpId", localWebUser.getCorpId());
	    
	    StringBuffer sql = new StringBuffer();
        sql.append("select t1.userId,t1.org_name,t1.userName,t1.status,t1.reason,t1.signed,t1.applyStatus,t1.signed_type,t1.isSigned,t1.signed_address,t1.qrcode_time,t1.position_time,t1.createdDate,t1.signedId from (");
        sql.append("select omni.notice_user_id userId,so.org_name,su.user_name userName,omni.status as status,omni.reason,omar.is_signed signed,omar.status applyStatus,omar.signed_type,");
        sql.append("omsi.is_signed isSigned,omsi.signed_address,omsi.qrcode_time,omsi.position_time,omsi.createdDate,omsi.id signedId from oa_meeting_notice_info omni ");
        sql.append("left join oa_meeting_signed_info omsi on omni.notice_user_id = omsi.signed_user_id and omsi.apply_record_id = :applyrecordId ");
        sql.append("left join oa_meeting_apply_record omar on omni.apply_record_id = omar.id ");
        sql.append("left join sys_user su on omni.notice_user_id = su.id ");
        sql.append("left join sys_org_user sou on omni.notice_user_id = sou.user_id and sou.isMain = 1 ");
        sql.append("left join sys_org so on sou.org_id = so.id and so.corp_id = :corpId ");
        sql.append("where omni.apply_record_id = :applyrecordId and omni.type = '1' and omni.status != 4 ");
        

        String noticeType = (String)paramMap.get("noticeType");
        LOGGER.debug("--paramMap.get(noticeType)-"+paramMap.get("noticeType"));
        if(StringUtils.isNotEmpty(noticeType)){//参会情况
            sql.append(" and omni.status = :noticeType ");
            localHashMap.put("noticeType", noticeType);
        }
        String signedType = (String)paramMap.get("signedType");
        LOGGER.debug("--paramMap.get(signedType)-"+paramMap.get("signedType"));
        if(StringUtils.isNotEmpty(signedType)){//签到情况
        	if("0".equals(signedType)){
        		sql.append(" and (omsi.is_signed is null or (omar.signed_type='2' and omsi.is_signed!='sd')) ");
        	}else{
        		sql.append(" and ((omar.signed_type=:signedType and omsi.is_signed='s') or (omar.signed_type=:signedType and omsi.is_signed='d') or (omar.signed_type=:signedType and omsi.is_signed='sd') or (omar.signed_type=:signedType and omsi.is_signed='xc')) ");
        		paramMap.put("signedType", signedType);
        	}
        }
        sql.append(") t1 where 1=1   order by t1.userName asc ");
	    
        LOGGER.debug("---sql:"+sql);
	    Query localQuery = getEntityManager().createNativeQuery(sql.toString());
	    SqlUtils.setQueryParameter(localHashMap, localQuery);
	    List<Object[]> localList = localQuery.getResultList();
	    NoticeInfo noticeInfo = null;
	    Object[] arrayOfObject = null;
	    LOGGER.debug("---localList.size():"+localList.size());
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
	    for (int i = 0; i < localList.size(); i++) {
	    	LOGGER.debug("---i:"+i);
	    	noticeInfo = new NoticeInfo();
	    	arrayOfObject = (Object[])localList.get(i);
	    	LOGGER.debug("---UserName:"+arrayOfObject[2]);
	    	noticeInfo.setUserName((String)arrayOfObject[2]);
	    	noticeInfo.setOrg_name((String)arrayOfObject[1]);
	    	noticeInfo.setSigned_address((String)arrayOfObject[9]);
	    	noticeInfo.setReason((String)arrayOfObject[4]);
	    	LOGGER.debug("---status:"+arrayOfObject[3]);
	    	String status = arrayOfObject[3]+"";
	    	if(status==null){
	    		noticeInfo.setStatusStr("");
	    	}else if("0".equals(status) || "9".equals(status)){
	    		noticeInfo.setStatusStr("未反馈");
	    	}else if("2".equals(status)){
	    		noticeInfo.setStatusStr("确认参会");
	    	}else if("3".equals(status)){
	    		noticeInfo.setStatusStr("不参会");
	    	}
	    	String isSigned = (String)arrayOfObject[8];
	    	String signed = arrayOfObject[5]+"";
	    	String signedtype = arrayOfObject[7]+"";
	    	LOGGER.debug("---isSigned:"+isSigned);
	    	LOGGER.debug("---signed:"+signed);
	    	LOGGER.debug("---signedtype:"+signedtype);
	    	
	    	if("0".equals(signed)){
	    		noticeInfo.setIsSignedStr("");
	    	}else{
	    		if(("0".equals(signedtype)&&"s".equals(isSigned)) || ("1".equals(signedtype)&&"d".equals(isSigned)) || 
				   ("2".equals(signedtype)&&"sd".equals(isSigned)) || ("3".equals(signedtype)&&"xc".equals(isSigned)) || 
				   (signedtype==null&&"1".equals(isSigned))){
	    			noticeInfo.setIsSignedStr("已签到");
	    		}else{
	    			noticeInfo.setIsSignedStr("未签到");
	    		}
	    	}
	    	LOGGER.debug("---positionTime_:"+arrayOfObject[11]);
	    	LOGGER.debug("---qrcodeTime_:"+arrayOfObject[10]);
	    	LOGGER.debug("---createdDate_:"+arrayOfObject[12]);
	    	Date positionTime_ = (Date)arrayOfObject[11];
	    	Date qrcodeTime_ = (Date)arrayOfObject[10];
	    	Date createdDate_ = (Date)arrayOfObject[12];
	    	
	    	String positionTime = "";
	    	if(positionTime_!=null) positionTime = sdf.format(positionTime_);
	    	String qrcodeTime = "";
	    	if(qrcodeTime_!=null) qrcodeTime = sdf.format(qrcodeTime_);
	    	String createdDate = "";
	    	if(createdDate_!=null) createdDate = sdf.format(createdDate_);
	    	
	    	LOGGER.debug("---positionTime:"+positionTime);
	    	LOGGER.debug("---qrcodeTime:"+qrcodeTime);
	    	LOGGER.debug("---createdDate:"+createdDate);
	    	if("1".equals(signed) && isSigned!=null && !"null".equals(isSigned) && !"".equals(isSigned)){
	    		if(positionTime_!=null && qrcodeTime_!=null){
	    			if(positionTime_.getTime() > qrcodeTime_.getTime()){
	    				noticeInfo.setSignedTime(positionTime); 
	    			}else{
	    				noticeInfo.setSignedTime(qrcodeTime); 
	    			}
	    		}else if(positionTime_ != null){
	    			noticeInfo.setSignedTime(positionTime); 
	    		}else if(qrcodeTime_ != null){
	    			noticeInfo.setSignedTime(qrcodeTime); 
	    		}else{
	    			noticeInfo.setSignedTime(createdDate); 
	    		}
	    	}else{
	    		noticeInfo.setSignedTime(""); 
	    	}
	    	
	    	noticeInfoList.add(noticeInfo);
	    }
	    LOGGER.debug("---noticeInfoList.size():"+noticeInfoList.size());
		return noticeInfoList;
	}

    /**
     * 查询会议参会详细
     * @param localPageable
     * @param applyrecordId
     * @param signedType 
     * @param noticeType 
     * @param token 
     * @return
     */
    public Page getUserDetailList(Pageable localPageable, String applyrecordId, String noticeType, String signedType, String token) {
        WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
        
        Map<String, Object> paramMap = new HashMap<String, Object>();
        StringBuffer sql = new StringBuffer();
        sql.append("select t1.userId,t1.org_name,t1.status,t1.reason,t1.signed,t1.applyStatus,t1.signed_type,t1.isSigned,t1.signed_address,t1.qrcode_time,t1.position_time,t1.createdDate,t1.signedId from (");
        
        sql.append("select omni.notice_user_id userId,so.org_name,omni.status as status,omni.reason,omar.is_signed signed,omar.status applyStatus,omar.signed_type,");
        sql.append("omsi.is_signed isSigned,omsi.signed_address,omsi.qrcode_time,omsi.position_time,omsi.createdDate,omsi.id signedId from (");
        
        sql.append("select omni.notice_user_id ,omni.apply_record_id,omni.type,omni.STATUS,omni.reason ");
        sql.append("from oa_meeting_notice_info omni ");
        sql.append("where omni.apply_record_id = :applyrecordId and omni.type = '1' and omni.status != 4 ");
        sql.append(") omni ");
        
        sql.append("left join oa_meeting_signed_info omsi on omni.notice_user_id = omsi.signed_user_id and omsi.apply_record_id = :applyrecordId ");
        sql.append("left join oa_meeting_apply_record omar on omni.apply_record_id = omar.id ");
        //sql.append("left join sys_user su on omni.notice_user_id = su.id ");
        sql.append("left join sys_org_user sou on omni.notice_user_id = sou.user_id and sou.isMain = 1 ");
        sql.append("left join sys_org so on sou.org_id = so.id and so.corp_id = :corpId ");
        sql.append(" where 1=1 ");
        
        paramMap.put("applyrecordId", applyrecordId);
        paramMap.put("corpId", corpId);
        if(StringUtils.isNotEmpty(noticeType)){//参会情况
            sql.append(" and omni.status = :noticeType ");
            paramMap.put("noticeType", noticeType);
        }
        if(StringUtils.isNotEmpty(signedType)){//签到情况
        	if("0".equals(signedType)){
        		sql.append(" and (omsi.is_signed is null or (omar.signed_type='2' and omsi.is_signed!='sd')) ");
        	}else{
        		sql.append(" and ((omar.signed_type=:signedType and omsi.is_signed='s') or (omar.signed_type=:signedType and omsi.is_signed='d') or (omar.signed_type=:signedType and omsi.is_signed='sd') or (omar.signed_type=:signedType and omsi.is_signed='xc')) ");
        		paramMap.put("signedType", signedType);
        	}
        	
        }
        sql.append(") t1 where 1=1 ");
        
        List localList = new ArrayList();
        String sqlStr = PropertyFilter.getSqlByFilterAndPageable("t1", sql.toString(), "t1.userId asc", localList, localPageable);
        Page<Map> localPage = this.findByPageNativeSQL(localPageable, sqlStr, paramMap);
        for(Map temp:localPage.getContent()) {
        	String userId=(String)temp.get("userId");
        	String userName=cmpPopUserOrgName.getUserNameById(userId);
        	temp.put("userName", userName);
        }
        return localPage;
    }

    /**
     * 会议管理定时任务  更新会议状态、发送会议提醒消息
     */
    public void handleApplyRecord(HttpServletRequest request) {
        //获取当前时间
        Date nowDateTime = DateUtils.parseTime(DateUtils.formatTimeNow());
        //未召开会议处理
        this.noApplyRecordHandle(nowDateTime, request);
        //进行中会议处理
        this.unApplyRecordHandle(nowDateTime);
    }
    
    /**
     * 会议管理定时任务  更新会议状态、发送会议提醒消息
     */
    public void handleJoinQS(HttpServletRequest request) {
    	LOGGER.info("----handleJoinQS----");
    	
        //获取当前时间
    	DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date nowDateTime = DateUtils.parseTime(DateUtils.formatTimeNow());
        
        long time = 30*60*1000;
        Date afterDate = new Date(nowDateTime.getTime() + time);
        
        //半小时后
		String strAfterDate = df.format(afterDate);
		LOGGER.info("---strAfterDate:"+strAfterDate);
		//查询要召开的网络会议
        List<ApplyRecord> webRecordlist = this.getWebApplyRecordList(strAfterDate);
        if(webRecordlist!=null) {
        	
        	String token = JwtUtils.resolveToken(request);
        	String fullPath = GlobalConstant.getFlexOfficeFullPath(request);
        	ApplyRecord entity = null;
        	Map<String, String> params = null;
        	//主持人id
        	String emceeUserId = "";
        	//全部参会人
        	List<String> qsUserList = null;
        	StringBuffer receiver = null;
        	
        	Map qsmeetingMap = null;
        	String msgLink = "";
        	for(int i=0;i<webRecordlist.size();i++) {
        		
        		entity = webRecordlist.get(i);

				emceeUserId = getEmceeUser(entity);
				qsUserList = getApplyRecordUserList(entity,token);
				receiver = new StringBuffer("[");
				String qsuserIds = "";
				if(qsUserList!=null&&qsUserList.size()>0){
					receiver.append("{\"10\":\"") ;
					String _ss = "";
					for(String userId : qsUserList) {
						if(userId!=null&&!"".equals(userId)) {
							_ss = _ss + userId+",";
						}
					}
					if(_ss.endsWith(",")) _ss.substring(0, _ss.length()-1);
					qsuserIds = _ss;
					receiver.append(_ss+"\"}") ;
				}
				receiver.append("]");
				LOGGER.info("-receiver:"+receiver);
				qsmeetingMap = qsMeetingService.getQsMeetingUrlById(entity.getId());
				msgLink = "modules/meeting/info/applyrecord_joinqsmeeting.html?emceeUserId="+emceeUserId+"&emeeUrl="+
				                   qsmeetingMap.get("emeeUrl")+"&attendUrl="+qsmeetingMap.get("attendUrl");
				LOGGER.info("---msgLink:"+msgLink);
				params = new HashMap<String, String>();
				params.put("corpId", entity.getCorpId());
				params.put("dataId", entity.getId());
				params.put("moduleCode", "meeting");
				params.put("moduleId", "402887ba6304b7e4016305aa85d90010");
				params.put("msgContent", "点击进入网络会议室");
				params.put("msgFmt", "1");
				params.put("msgLevel", "3");
				params.put("msgLink", msgLink);
				params.put("msgTitle", "入会提醒：请点击链接进入"+entity.getName()+"网络会议室");
				params.put("msgReceiver", receiver.toString());
				params.put("msgSender", "1111");
				params.put("msgSenderType", "00");
				params.put("msgType", "1");
				params.put("paramString", "");
				params.put("createdDate", DateUtils.formatTimeNow());
				params.put("openMode", "0");
				
				String paramStr = JsonUtils.writeValueAsString(params);
				LOGGER.info("-paramStr:"+paramStr);
				LOGGER.info("-paramStr:"+paramStr);
				SendMsgThread smt = new SendMsgThread(token, "pc", paramStr);
		     	smt.start();
		     	
		     	Map<String,String> msgTypeMap = new HashMap<String, String>();
		     	msgTypeMap.put("MH", "news");
		     	
	        	String context = MeetingSendMsgUtils.convertContextPath(fullPath);
	        	String menhuFront = GlobalConstant.getConfig("app.mobile.menhu.front.url");
		     	String messageUrl = "/mobile/modules/meeting/dist/index.html?contextPath=" + context
        				+ "&dd_nav_bgcolor=FF5E97F6#/meeting/meetingQS/"+entity.getId();
		     	String message = "{\"articles\" : [{" + 
						"\"title\" : \""+entity.getName()+"\"," + 
						"\"description\" : \"点击进入网络会议\"," + 
						"\"appUrl\" : \"" + menhuFront + messageUrl + "\"" + 
					"}]}";
		     	LOGGER.info("-message:"+message);
		     	Map<String,Object> messageContent = new HashMap<String,Object>();
		     	messageContent.put("news", JsonUtils.readValue(message));
		     	Map<String,Object> messageMap = new HashMap<String, Object>();
            	messageMap.put("MH", messageContent);
            	
		     	SendMsgThread smtApp = new SendMsgThread(msgTypeMap, messageMap, "meeting", 
		     			                                 entity.getCorpId(), qsuserIds, "", fullPath, "app");
		     	smtApp.start();
		     	LOGGER.info("-end---");
        	}
        }
    }
    
    /**
     * 定时任务：未召开会议处理
     * @param token 
     */
    public void noApplyRecordHandle(Date nowDateTime, HttpServletRequest request){
    	LOGGER.debug("------noApplyRecordHandle-------");
        List<String> list = new ArrayList<String>();
        String dateRegex="\\d{4,4}-\\d{2,2}-\\d{2,2} \\d{2,2}:\\d{2,2}";
        //查询未召开的会议
        List<ApplyRecord> noApplyRecordlist = this.getApplyRecordList(1);
        if(noApplyRecordlist!=null && noApplyRecordlist.size()>0){
            for(ApplyRecord applyRecord : noApplyRecordlist){
            	if(applyRecord.getStartTime()==null) {
            		continue;
            	}
            	if(!Pattern.matches(dateRegex, applyRecord.getStartTime())) {
            		continue;
            	}
                //会议开始时间
                String startDate = applyRecord.getStartTime() + ":00";
                Date startDateTime = DateUtils.parseTime(startDate);
                if(nowDateTime.getTime()>=startDateTime.getTime()){//当前时间>会议开始时间
                    //修改会议状态
                    list.add(applyRecord.getId());
                }else{
                    //会议是否开启会前提醒
                    int isNotice = applyRecord.getIsNotice();
                    LOGGER.debug("---isNotice:"+isNotice);
                    if(isNotice==1){//会议开启会前提醒
                        //List<String> noticeTypeList = new ArrayList<String>();
                        String noticeType = applyRecord.getNoticeType();
                        String noticeTime = applyRecord.getNoticeTime();
                        LOGGER.debug("---noticeTime:"+noticeTime);
                        Date noticeStartDate = DateUtils.addMinutes(startDateTime, -Integer.parseInt(noticeTime));
                        Date maxLimit = DateUtils.addMinutes(noticeStartDate, 5);
                        if(nowDateTime.getTime()>=noticeStartDate.getTime() && nowDateTime.getTime() < maxLimit.getTime()){//当前时间>会议提醒时间
                        	LOGGER.debug("---noticeType:"+noticeType);
                            //if(StringUtils.isNotEmpty(noticeType)){
                                //根据提醒方式发送会议提醒消息
                                //noticeTypeList = Arrays.asList(noticeType.split(","));
                                //调用发送会议消息
                                //this.sendMessageService.send(applyRecord,noticeTypeList,1,token);
                                //发送钉钉推送
                                //if(noticeType.indexOf("2")!=-1){
                                	String corpId = applyRecord.getCorpId();
                                	Map<String, Object> ds = new HashMap<>();
                                	ds.put("type", "4");
                                	ds.put("noticeTime", noticeTime);
                        			ds.put("applyRecordId", applyRecord.getId());
                        			ds.put("meetingTitle", applyRecord.getName());
                        			ds.put("startTime", applyRecord.getStartTime());
                        			if(StringUtils.isNotEmpty(applyRecord.getBoardroomId())) {
                        				BoardroomSet room = this.boardroomSetService.findOne(applyRecord.getBoardroomId());
                            			ds.put("boardroom", room.getAddress());
                        			}else {
                        				ds.put("boardroom", StringUtils.isNotEmpty(applyRecord.getAddress()) ? applyRecord.getAddress():"无");
                        			}
                        			String noticeUserId = applyRecord.getCreatedBy();
                        			ds.put("userId", noticeUserId);
                        			String token = JwtUtils.resolveToken(request);
                        			String noticeUserName = "";
                        			if(StringUtils.isNoneEmpty(noticeUserId)) {
                        				Map<String, Object> map = userApiService.getUser(noticeUserId, corpId, "", token);
                        				if(MapUtils.isNotEmpty(map)) {
                        					noticeUserName = StringUtils.null2String(map.get("userName"));
                        				}
                        			}
                        			ds.put("userName", noticeUserName);
                        			ds.put("userOrg", applyRecord.getCreatedOrg());
                        			//Map<String, String> map = this.getUserThirdIds(applyRecord.getEmceeUser(), applyRecord.getMemoUser(), applyRecord.getAttendUser(), corpId);
                        			List<String> userIdList = this.getApplyRecordUserList(applyRecord, token);
                        			if(CollectionUtils.isNotEmpty(userIdList)){
                        				StringBuffer ids = new StringBuffer();
                        				StringBuffer jsonIds = new StringBuffer("[");
                        				for(int i = 0; i < userIdList.size(); i++) {
                        					if(i == userIdList.size() - 1) {
                        						ids.append(userIdList.get(i));
                        						jsonIds.append("{\"10\":\"" + userIdList.get(i) + "\"}]");
                        					}else {
                        						ids.append(userIdList.get(i) + ",");
                        						jsonIds.append("{\"10\":\"" + userIdList.get(i) + "\"},");
                        					}
                        				}
                        				jsonIds.append("]");
                        				LOGGER.debug("---ids:"+ids);
                        				if(StringUtils.isNotEmpty(ids.toString())){
                        					ds.put("userIds", ids.toString());
                            				ds.put("orgIds", "");
                        					boolean mobilePush = false;
                        		            boolean emailPush = false;
                        		            boolean smsPublish = false;
                        					String mesgPush = applyRecord.getMessagePush();
                        					if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("mobile")) mobilePush = true;
                        					if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("email")) emailPush = true;
                        					if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("sms")) smsPublish = true;
                        					this.meetingSendMsgUtils.sendMail(ds, emailPush, corpId, token);
                        					this.meetingSendMsgUtils.sendMsgToApp(ds, mobilePush, corpId, token, request);
                        					this.meetingSendMsgUtils.sendSMS(ds, smsPublish, corpId, token);
                        				}
                        				LOGGER.debug("---jsonIds:"+jsonIds);
                                        if(!"[]".equals(jsonIds.toString())){
                                        	this.meetingSendMsgUtils.sendMessage(ds, jsonIds.toString(), corpId, token);
                                        }
                        			}
                                //}
                            //}
                        }
                    }
                }
            }
        }
        //保存会议新状态
        if(list!=null && list.size()>0){
            this.dao.updApplyRecord(4, list);
        }
    }
    
    public Map<String, String> getUserThirdIds(String emceeUser, String memoUser, String attendUser, String corpId){
    	Map<String, String> map = new HashMap<>();
//    	List<String> userIds = new ArrayList<>();
    	String ids = "";
    	String oIds = "";
    	String jsonIds = "[";
		//主持人
        List<String> eScopeList = new ArrayList<>();
        eScopeList.add(emceeUser);
        List<MeetingScope> emceeUserList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "emcee_user", eScopeList,true);
        if(emceeUserList != null && emceeUserList.size()>0){
            String userId = emceeUserList.get(0).getScopevalue();
//        	userIds.add(userId);
            jsonIds +="{\"10\":\""+userId+"\"},";
            ids += userId + ",";
        }
        //纪要员
        List<String> mScopeList = new ArrayList<>();
        mScopeList.add(memoUser);
        List<MeetingScope> memoUserList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "memo_user", mScopeList,true);
        if(memoUserList!=null && memoUserList.size()>0){
            String userId = memoUserList.get(0).getScopevalue();
//            userIds.add(userId);
            jsonIds +="{\"10\":\""+userId+"\"},";
            ids += userId + ",";
        }
        
        //参会员
        List<String> aScopeList = new ArrayList<>();
        aScopeList.add(attendUser);
        List<MeetingScope> attendUserList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "attend_user", aScopeList,true);
//        List<String> orgIds = new ArrayList<>();
        String type = "", value = "";
        if(attendUserList != null && attendUserList.size()>0){
        	for (MeetingScope scope : attendUserList) {
        		type = scope.getScopetype();
        		value = scope.getScopevalue();
        		if("user".equals(type)){
//        			userIds.add(value);
                    jsonIds +="{\"10\":\""+value+"\"},";
                    ids += value + ",";
        		}else if("org".equals(type)){
//        			orgIds.add(value);
                    jsonIds +="{\"20\":\""+value+"\"},";
                    oIds += value + ",";
        		}
			}
        }
//        //人员
//        StringBuffer sql1 = new StringBuffer();
//        String ids = "";
//        sql1.append("select dd_uid from sys_user where id in (?1) ");
//        Query query1 = super.getEntityManager().createNativeQuery(sql1.toString()).setParameter(1, userIds);
//        List<Object> result1 = query1.getResultList();
//		if(result1 != null){
//			for (Object id : result1) {
//				if(id != null){
//					ids += id + ",";
//				}
//			}
//		}
//
//        //部门
//        String oIds = "";
//        if(orgIds!=null && orgIds.size()>0){
//        	StringBuffer sql2 = new StringBuffer();
//            sql2.append("select dd_uid from sys_org where id in (?1) ");
//            Query query2 = super.getEntityManager().createNativeQuery(sql2.toString()).setParameter(1, orgIds);
//            List<Object> result2 = query2.getResultList();
//    		if(result2 != null){
//    			for (Object id : result2) {
//    				if(id != null){
//    				    if("1".equals(id)){
//                            String sql3 = "select su.dd_uid from sys_user su left join sys_org_user sou on su.id = sou.user_id where sou.org_id in (select id from sys_org where dd_uid='1' and corp_id in (?1)) ";
//                            Query query3 = super.getEntityManager().createNativeQuery(sql3).setParameter(1, corpId);
//                            List<Object> result3 = query3.getResultList();
//                            if(result3 != null){
//                                for (Object ddUid : result3) {
//                                    if(ddUid != null){
//                                        ids += ddUid + ",";
//                                    }
//                                }
//                            }
//                            String sql4 = "select dd_uid from sys_org where parent_id in (select id from sys_org where dd_uid='1' and corp_id in (?1)) ";
//                            Query query4 = super.getEntityManager().createNativeQuery(sql4).setParameter(1, corpId);
//                            List<Object> result4 = query4.getResultList();
//                            if(result4 != null){
//                                for (Object ddUid : result4) {
//                                    if(ddUid != null){
//                                        oIds += ddUid + ",";
//                                    }
//                                }
//                            }
//                        }else{
//                            oIds += id + ",";
//                        }
//    				}
//    			}
//    		}
//        }
        if(!StringUtils.isEmpty(ids)){
            ids = ids.substring(0, ids.length()-1);
        }
        map.put("userIds", ids);
        if(!StringUtils.isEmpty(oIds)){
            oIds = oIds.substring(0, oIds.length()-1);
        }
        map.put("orgIds", oIds);
        if(StringUtils.isNotEmpty(jsonIds)){
            jsonIds = jsonIds.substring(0, jsonIds.length()-1);
        }
        map.put("jsonIds", jsonIds + "]");
		return map;
    }
    
    /**
     * 定时任务：进行中会议处理
     * @param nowDateTime 
     * @param token 
     */
    public void unApplyRecordHandle(Date nowDateTime){
        List<String> list = new ArrayList<>();
        //查询进行中的会议
        List<ApplyRecord> unApplyRecordlist = this.getApplyRecordList(4);
        if(unApplyRecordlist!=null && unApplyRecordlist.size()>0){
            for(ApplyRecord applyRecord : unApplyRecordlist){
                //会议开始时间
                if(applyRecord != null){
                	String endTime = applyRecord.getEndTime()+":59";
                    Date endDateTime = DateUtils.parseTime(endTime);
                    if(nowDateTime.getTime()>=endDateTime.getTime()){//当前时间>会议结束时间
                        //修改会议状态
                        list.add(applyRecord.getId());
                    }
                }
            }
        }

        //保存会议新状态
        if(list!=null && list.size()>0){
            this.dao.updApplyRecord(5, list);
        }
    }
    
    /**
     * 查询会议集合
     * @param status
     * @return
     */
    public List<ApplyRecord> getApplyRecordList(int status){
        return this.dao.getApplyRecordList(status);
    }
    
    /**
     * 网络会议
     * @param status
     * @param meetingWay
     * @return
     */
    public List<ApplyRecord> getWebApplyRecordList(String startTime){
        return this.dao.getWebApplyRecordList(startTime);
    }
    
    /**
     * 获取会议的参会人、组织、群组、岗位
     * @param applyRecord
     * @param token
     * @return
     */
    public List<String> getApplyRecordAttendPeopleList(ApplyRecord applyRecord,String token){
        //主持人
        List<String> eScopeList = new ArrayList<>();
        eScopeList.add(applyRecord.getEmceeUser());
        List<MeetingScope> emceeUserList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "emcee_user", eScopeList,true);
        //纪要员
        List<String> mScopeList = new ArrayList<>();
        mScopeList.add(applyRecord.getMemoUser());
        List<MeetingScope> memoUserList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "memo_user", mScopeList,true);
        //参会员
        List<String> aScopeList = new ArrayList<>();
        aScopeList.add(applyRecord.getAttendUser());
        List<MeetingScope> attendUserList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "attend_user", aScopeList,true);
        Set<String> peopleList = new HashSet<String>();
        if(emceeUserList!=null && emceeUserList.size()>0){
            for(MeetingScope ms : emceeUserList){
                String scopeValue = ms.getScopevalue();
                peopleList.add(scopeValue);
            }
        }
        if(memoUserList!=null && memoUserList.size()>0){
            for(MeetingScope ms : memoUserList){
                String scopeValue = ms.getScopevalue();
                peopleList.add(scopeValue);
            }
        }
        if(attendUserList!=null && attendUserList.size()>0){
            for(MeetingScope ms : attendUserList){
            	String scopeValue = ms.getScopevalue();
            	peopleList.add(scopeValue);
            }
        }
        return  new ArrayList<String>(peopleList);
    }
    
    public List<String> getApplyRecordUserList(ApplyRecord applyRecord,String token){
    	
    	String curUserId = applyRecord.getCreatedBy();
        String corpId = applyRecord.getCorpId();
        //主持人
//        List<String> eScopeList = new ArrayList<>();
//        eScopeList.add(applyRecord.getEmceeUser());
//        List<MeetingScope> emceeUserList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "emcee_user", eScopeList,true);
//        //纪要员
//        List<String> mScopeList = new ArrayList<>();
//        mScopeList.add(applyRecord.getMemoUser());
//        List<MeetingScope> memoUserList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "memo_user", mScopeList,true);
//        //参会员
//        List<String> aScopeList = new ArrayList<>();
//        aScopeList.add(applyRecord.getAttendUser());
//        List<MeetingScope> attendUserList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "attend_user", aScopeList,true);
        List<String> scopeList= new ArrayList<>();
        scopeList.add(applyRecord.getEmceeUser());
        scopeList.add(applyRecord.getMemoUser());
        scopeList.add(applyRecord.getAttendUser());
        scopeList.add(applyRecord.getMeetingAttendants());
        String sqlWhereFieldDataValue=MeetingUtils.getWhereInValuesSql("fieldDataValue", scopeList, 1000);
        String sql="select scopeType,scopeValue from oa_meeting_apply_record_scope t where t.fieldDataTable='oa_meeting_apply_record' and (t.fieldData='attend_user' or t.fieldData='emcee_user' or t.fieldData='memo_user' or t.fieldData='meeting_attendants')and "+sqlWhereFieldDataValue;
        List<Map> applyUserList=this.meetingScopeService.findByListNativeQuery(sql,null);
        Set<String> userList = new HashSet<String>();
        //为全时修改，发起人默认是主持人，并发通知
        userList.add(curUserId);
        List<String> unitUserList = null;
        for(Map ms : applyUserList){
            String scopeValue = (String)ms.get("scopeValue");
            String scopeType = (String)ms.get("scopeType");
            if("user".equals(scopeType)){
                userList.add(scopeValue);
            }else if("org".equals(scopeType)){
            	unitUserList = this.userApiService.getUserIdsByOrgId(scopeValue, "", "1", corpId, token);
                if(CollectionUtils.isNotEmpty(unitUserList)){
                    userList.addAll(unitUserList);
                }
            }else if("group".equals(scopeType)){
            	unitUserList = this.userApiService.getUserIdsByGrpId(scopeValue, "1", corpId, token);
                if(CollectionUtils.isNotEmpty(unitUserList)){
                	userList.addAll(unitUserList);
                }
            }else if("station".equals(scopeType)){
            	unitUserList = this.userApiService.getUserIdsByStationId(scopeValue, "1", corpId, token);
                if(CollectionUtils.isNotEmpty(unitUserList)){
                	userList.addAll(unitUserList);
                }
            }else if("personalGroup".equals(scopeType)){
            	unitUserList = this.grpUserService.getGroupUser(scopeValue);
                if(CollectionUtils.isNotEmpty(unitUserList)){
                	userList.addAll(unitUserList);
                }
            }
        }
//        if(emceeUserList!=null && emceeUserList.size()>0){
//            for(MeetingScope ms : emceeUserList){
//                String scopeValue = ms.getScopevalue();
//                userList.add(scopeValue);
//            }
//        }
//        
//        if(memoUserList!=null && memoUserList.size()>0){
//            for(MeetingScope ms : memoUserList){
//                String scopeValue = ms.getScopevalue();
//                userList.add(scopeValue);
//            }
//        }
        
//        if(attendUserList!=null && attendUserList.size()>0){
//        	List<String> unitUserList = null;
//            for(MeetingScope ms : attendUserList){
//                String scopeValue = ms.getScopevalue();
//                String scopeType = ms.getScopetype();
//                if("user".equals(scopeType)){
//                    userList.add(scopeValue);
//                }else if("org".equals(scopeType)){
//                	unitUserList = this.userApiService.getUserIdsByOrgId(scopeValue, "", "1", corpId, token);
//                    if(CollectionUtils.isNotEmpty(unitUserList)){
//                        userList.addAll(unitUserList);
//                    }
//                }else if("group".equals(scopeType)){
//                	unitUserList = this.userApiService.getUserIdsByGrpId(scopeValue, "1", corpId, token);
//                    if(CollectionUtils.isNotEmpty(unitUserList)){
//                    	userList.addAll(unitUserList);
//                    }
//                }else if("station".equals(scopeType)){
//                	unitUserList = this.userApiService.getUserIdsByStationId(scopeValue, "1", corpId, token);
//                    if(CollectionUtils.isNotEmpty(unitUserList)){
//                    	userList.addAll(unitUserList);
//                    }
//                }else if("personalGroup".equals(scopeType)){
//                	unitUserList = this.grpUserService.getGroupUser(scopeValue);
//                    if(CollectionUtils.isNotEmpty(unitUserList)){
//                    	userList.addAll(unitUserList);
//                    }
//                }
//            }
//        }
        
        return  new ArrayList<String>(userList);
    }
    /**
     * 获取主持人id
     * @param applyRecord
     * @return
     */
    public String getEmceeUser(ApplyRecord applyRecord){
        //主持人
        List<String> eScopeList = new ArrayList<>();
        eScopeList.add(applyRecord.getEmceeUser());
        List<MeetingScope> emceeUserList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "emcee_user", eScopeList,true);
        String emceeUserId = "";
        if(emceeUserList!=null && emceeUserList.size()>0){
            for(MeetingScope ms : emceeUserList){
            	emceeUserId = ms.getScopevalue();
            }
        }
        return emceeUserId;
    }
    /**
     * 获取参数人（去除去主持人）
     * @param applyRecord
     * @param token
     * @return
     */
    public List<String> getAttendUserList(ApplyRecord applyRecord,String token){
    	
        String corpId = applyRecord.getCorpId();
        //纪要员
        List<String> mScopeList = new ArrayList<>();
        mScopeList.add(applyRecord.getMemoUser());
        List<MeetingScope> memoUserList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "memo_user", mScopeList,true);
        //参会员
        List<String> aScopeList = new ArrayList<>();
        aScopeList.add(applyRecord.getAttendUser());
        List<MeetingScope> attendUserList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "attend_user", aScopeList,true);
        
        Set<String> userList = new HashSet<String>();
        
        if(memoUserList!=null && memoUserList.size()>0){
            for(MeetingScope ms : memoUserList){
                String scopeValue = ms.getScopevalue();
                userList.add(scopeValue);
            }
        }
        
        if(attendUserList!=null && attendUserList.size()>0){
        	List<String> unitUserList = null;
            for(MeetingScope ms : attendUserList){
                String scopeValue = ms.getScopevalue();
                String scopeType = ms.getScopetype();
                if("user".equals(scopeType)){
                    userList.add(scopeValue);
                }else if("org".equals(scopeType)){
                	unitUserList = this.userApiService.getUserIdsByOrgId(scopeValue, "", "1", corpId, token);
                    if(CollectionUtils.isNotEmpty(unitUserList)){
                        userList.addAll(unitUserList);
                    }
                }else if("group".equals(scopeType)){
                	unitUserList = this.userApiService.getUserIdsByGrpId(scopeValue, "1", corpId, token);
                    if(CollectionUtils.isNotEmpty(unitUserList)){
                    	userList.addAll(unitUserList);
                    }
                }else if("station".equals(scopeType)){
                	unitUserList = this.userApiService.getUserIdsByStationId(scopeValue, "1", corpId, token);
                    if(CollectionUtils.isNotEmpty(unitUserList)){
                    	userList.addAll(unitUserList);
                    }
                }
            }
        }
        
        return  new ArrayList<String>(userList);
    }
    
    /**
     * 计算有效时间
     * @param subRecordDate
     * @param onWorkTime
     * @param onWorkBefore
     * @param type 0:相加 1:相减
     * @return
     */
    public String getDateTimeStr(String dateTime, int data,int type) {
        String hourStr = "";
        String minStr = "";
        String[] arr = dateTime.split(":");
        int hour =Integer.valueOf(arr[0]);
        int min = Integer.valueOf(arr[1]);
        if(type==0){//相加计算
            hour = hour + (data+min)/60;
            min =(data+min)-(data+min)/60*60;
        }else if(type==1){//相减计算
            for(int i=0;i<hour;i++){
                if(((i*60+min)-data)>0){
                    hour = (hour-i);
                    min = (i*60+min)-data;
                    break;
                }
            }
        }
        if(hour<10){
            hourStr = "0" + hour;
        }else{
            hourStr = "" + hour;
        }
        if(min<10){
            minStr = "0" + min;
        }else{
            minStr = "" + min;
        }
        return hourStr + ":"+ minStr;
    }

    // 前后端分离前的
    public List<Map<String,Object>> getApplyRecordInfo(List<BoardroomSet> bsList,String startDate,String endDate,Map<String, String> params) {
        //List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
    	List<Map<String,Object>> listMap = new ArrayList<Map<String,Object>>();
        if(bsList!=null && bsList.size()>0){
        	for(BoardroomSet bs : bsList){
//            	BoardroomCategorySet set = this.categoryDao.findById(bs.getCategoryId()).get();
//            	if(set == null){
//            		continue;
//            	}
                //Map<String,Object> boardroomMap = new HashMap<String,Object>(); 
                
                String boardroomSetId = bs.getId();
                String bsStartTime = startDate + " " + bs.getStartTime()+":00";
                String bsEnd = bs.getEndTime();
                if("24:00".equals(bsEnd)){
                	bsEnd = "23:59";
                }
    			String bsEndTime = endDate + " " + bsEnd +":59";
    			Date boardStart = DateUtils.parseTime(bsStartTime);
                Date boardEnd = DateUtils.parseTime(bsEndTime);
    			
                String startDateStr = startDate + " 00:00:00";
                String endDateStr = endDate + " 23:59:59";
                //List<ApplyRecord> arList = this.dao.getApplyRecordList(boardroomSetId,startDateStr,endDateStr);
                List<Map> arList = getApplyrecordData(boardroomSetId,startDateStr,endDateStr);
                if(arList!=null && arList.size()>0){
                    for(int i=0;i<arList.size();i++){
                    	Map applyRecord = arList.get(i);
                        Map<String,Object> timeUsedMap = new HashMap<String,Object>(); 
                        timeUsedMap.put("title", applyRecord.get("name"));
                        String start = applyRecord.get("start_time")+":00";
                        String end = applyRecord.get("end_time")+":00";
                        Date meetingStart = DateUtils.parseTime(start);
                        Date meetingEnd = DateUtils.parseTime(end);
                        if(startDate.equals(endDate) && meetingStart.getTime()<boardStart.getTime()){
                        	timeUsedMap.put("start",bsStartTime);
                        }else{
                        	timeUsedMap.put("start",start);
                        }
                        if(startDate.equals(endDate) && meetingEnd.getTime() > boardEnd.getTime()){
                        	timeUsedMap.put("end",bsEndTime);
                        }else{
                        	timeUsedMap.put("end",end);
                        }
                        timeUsedMap.put("startTime",start);
                        timeUsedMap.put("endTime",end);
                        timeUsedMap.put("create", applyRecord.get("user_name"));
                        timeUsedMap.put("resourceId", applyRecord.get("boardroom_id"));
                        timeUsedMap.put("color", "#FF9933");
//                        int status = Integer.parseInt(StringUtils.null2String(applyRecord.get("status")));
                        timeUsedMap.put("block", false);
                        /*if(status==2 || status==3 || status==5){
                        	timeUsedMap.put("block", false);
                        }else{
                        	timeUsedMap.put("block", true);
                        }*/
                        timeUsedMap.put("canView", this.viewMeeting(applyRecord, params));
                        timeUsedMap.put("applyrecordId", applyRecord.get("id"));
                        timeUsedMap.put("meetingStatus", applyRecord.get("status"));
                        listMap.add(timeUsedMap);
                    }
                }
                //boardroomMap.put("boardroomSet", bs);
                //boardroomMap.put("applyRecordListMap", listMap);
                //list.add(boardroomMap);
            }
        }
        return listMap;
    }
    
    /**
     * 会议预定日历，获取会议信息
     * @param bsList
     * @param startDate
     * @param endDate
     * @param params
     * @return
     */
    public List<Map<String,Object>> getApplyRecordInfos(List<Map> bsList, List<String> bsIdsList,String startDate,String endDate,Map<String, String> params) {
    	List<Map<String,Object>> listMap = new ArrayList<Map<String,Object>>();
        if(bsList!=null && bsList.size()>0){
        	String startDateStr = startDate + " 00:00:00";
            String endDateStr = endDate + " 23:59:59";
        	List<Map> arList = getApplyrecordData(bsIdsList, startDateStr, endDateStr);
        	for(Map bs : bsList){
        		String boardroomSetId = StringUtils.null2String(bs.get("id"));
                String bsStartTime = startDate + " " + StringUtils.null2String(bs.get("startTime"))+":00";
                String bsEnd = StringUtils.null2String(bs.get("endTime"));
                if("24:00".equals(bsEnd)){
                	bsEnd = "23:59";
                }
    			String bsEndTime = endDate + " " + bsEnd +":59";
    			Date boardStart = DateUtils.parseTime(bsStartTime);
                Date boardEnd = DateUtils.parseTime(bsEndTime);
               
                if(arList!=null && arList.size()>0){
                	String userId = params.get("userId");
                	String token = params.get("token");
                	Map<String,String>textParams=new HashMap<>();
        			textParams.put("code", "meeting:meeting:03");
        			textParams.put("userId", userId);
        			String jsonStr = this.restClient.get("/system/permission/hasPermission", token, textParams);
        			Map<String, Object> result = JsonUtils.readValue(jsonStr);
        			boolean isView=false;
        			if("1".equals(result.get("data"))) {
        				isView=true;
        			}
                    for(int i=0;i<arList.size();i++){
                    	Map applyRecord = arList.get(i);
                    	if(StringUtils.equals(boardroomSetId, StringUtils.null2String(applyRecord.get("boardroom_id")))) {
                    		Map<String,Object> timeUsedMap = new HashMap<String,Object>(); 
                    		if("0".equals(String.valueOf(applyRecord.get("status")))) {
                    			 timeUsedMap.put("title", "预约中时段");
                    		}else
                    			timeUsedMap.put("title", applyRecord.get("name"));
                            String start = applyRecord.get("start_time")+":00";
                            String end = applyRecord.get("end_time")+":00";
                            Date meetingStart = DateUtils.parseTime(start);
                            Date meetingEnd = DateUtils.parseTime(end);
                            if(startDate.equals(endDate) && meetingStart.getTime()<boardStart.getTime()){
                            	timeUsedMap.put("start",bsStartTime);
                            }else{
                            	timeUsedMap.put("start",start);
                            }
                            if(startDate.equals(endDate) && meetingEnd.getTime() > boardEnd.getTime()){
                            	timeUsedMap.put("end",bsEndTime);
                            }else{
                            	timeUsedMap.put("end",end);
                            }
                            timeUsedMap.put("startTime",start);
                            timeUsedMap.put("endTime",end);
                            timeUsedMap.put("create", applyRecord.get("user_name"));
                            timeUsedMap.put("createdBy", applyRecord.get("createName"));
                            
                            timeUsedMap.put("orgName", applyRecord.get("orgName"));
                            timeUsedMap.put("resourceId", applyRecord.get("boardroom_id"));
                            timeUsedMap.put("color", "#FF9933");
                            timeUsedMap.put("block", false);
                            if(isView) {
                            	timeUsedMap.put("canView", true);
                            }else
                            timeUsedMap.put("canView", this.viewMeeting(applyRecord, params));
                            
                            timeUsedMap.put("applyrecordId", applyRecord.get("id"));
                            timeUsedMap.put("meetingStatus", applyRecord.get("status"));
                            listMap.add(timeUsedMap);
                    	}
                    }
                }
            }
        }
        return listMap;
    }
    
    public List<Map> getApplyrecordData(String bsId, String startDateStr, String endDateStr) {
    	List<String> bsIdsList = new ArrayList<String>();
    	bsIdsList.add(bsId);
    	return getApplyrecordData(bsIdsList, startDateStr, endDateStr);
    }
    
    public List<Map> getApplyrecordData(List<String> bsIdsList, String startDateStr, String endDateStr) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        StringBuffer sql = new StringBuffer();
        sql.append("select omar.id,omar.name,omar.start_time,omar.end_time,omar.boardroom_id,omar.status,omar.createdBy,");
        sql.append(" omar.emcee_user,omar.memo_user,omar.attend_user,omar.meeting_attendants,u.user_name ");
        sql.append(" from oa_meeting_apply_record omar");
        sql.append(" left join oa_meeting_apply_record_scope oms on omar.emcee_user=oms.fieldDataValue and oms.fieldData='emcee_user'");
        sql.append(" left join sys_user u on oms.scopeValue=u.id");
        sql.append(" where omar.boardroom_id in (:bsIdsList) and ((omar.start_time between :startDateStr and :endDateStr) or (omar.end_time between :startDateStr and :endDateStr)");
        sql.append("  or (omar.start_time <=:startDateStr and omar.end_time >= :endDateStr)) and omar.status in ('0','1','4','5') order by omar.start_time asc");
        paramMap.put("bsIdsList", bsIdsList);
        paramMap.put("startDateStr", startDateStr);
        paramMap.put("endDateStr", endDateStr);
        List<Map> list = super.findByListNativeQuery(sql.toString(), "", paramMap);
        if(list!=null) {
        	 String orgName="";
        	for(Map ele:list) {
        		orgName=StringUtils.null2String(cmpPopUserOrgName.getOrgNameByUserId((String)ele.get("createdBy")));
                if(orgName.lastIndexOf("/")>-1) {
                	orgName=orgName.substring(orgName.lastIndexOf("/"));
                	if(orgName.length()>1) {
                		orgName=orgName.substring(1);
                	}
                }
        		ele.put("createName", cmpPopUserOrgName.getUserNameById((String)ele.get("createdBy")));
        		ele.put("orgName", orgName);
            }
        }
        
        return list;
    }

    /**
     * 
     * @param startDate
     * @param endDate
     * @param params
     * @param type  0:全部 1：我发起的  2：我参加的 
     * @return
     */
    public List<Map<String,Object>> getCalendarApplyRecordInfo(String startDate, String endDate, Map<String, String> params,String type) {
    	
    	LOGGER.debug("-----getCalendarApplyRecordInfo----");
    	LOGGER.debug("-type:"+type);
        List<Map<String,Object>> listMap = new ArrayList<Map<String,Object>>();
        String startDateStr = startDate + " 00:00:00";
        String endDateStr = endDate + " 23:59:59";
        String userId = params.get("userId");
        String corpId = params.get("corpId");
        String token = params.get("token");
        StringBuffer sql = new StringBuffer();
        
        Map<String, Object> paramMap = new HashMap<String, Object>();
        sql.append("select id,name,start_time,end_time,createdBy,status,boardroom_id ");
        sql.append(" from oa_meeting_apply_record where corp_id =:corpId and is_sync=1 ");
        
 	    List<String> unitorgList = this.orgApiService.getOrgIdsByUserIds(userId, corpId, "", "2", token);
 	    if(unitorgList==null){
            unitorgList = new ArrayList<String>();
        }
        unitorgList.add(userId);
        
        
//        sql.append(" and ((((status ='3' and createdBy =:userId) or status in ('1','4','5'))");
//        sql.append(" and");
//        sql.append(" (emcee_user in(select fieldDataValue from oa_meeting_apply_record_scope where scopeValue =:userId)");
//        sql.append(" or memo_user in(select fieldDataValue from oa_meeting_apply_record_scope where scopeValue =:userId)");
//        sql.append(" or attend_user in(select fieldDataValue from oa_meeting_apply_record_scope where scopeValue in(:unitorgList))))");
//        sql.append(" or (createdBy =:userId and status not in ('-1', '0', '6', '2'))) ");
//        sql.append(" and ((start_time between :startDateStr and :endDateStr) or (end_time between :startDateStr and :endDateStr)");
//        sql.append(" or (start_time <= :startDateStr and end_time >= :endDateStr)) order by start_time asc");
      
        //status : 0/申请中，1/未召开，2/已驳回，3/已取消，4/进行中，5/已结束，6/草稿箱
        
        paramMap.put("corpId", corpId);
        //我发起的
	    if("1".equals(type)) {
	    	
	        sql.append(" and (createdBy =:userId and status in ('1','3','4','5'))  ");
	        sql.append(" and ((start_time between :startDateStr and :endDateStr) or (end_time between :startDateStr and :endDateStr)");
	        sql.append(" or (start_time <= :startDateStr and end_time >= :endDateStr) ) ");
	        
	        paramMap.put("startDateStr", startDateStr);
	        paramMap.put("endDateStr", endDateStr);
	        paramMap.put("userId", userId);
	    }else if("2".equals(type)) {   //我参与的
	    	
	        sql.append(" and status in ('1','4','5')");
	        sql.append(" and (emcee_user in(select fieldDataValue from oa_meeting_apply_record_scope where scopeValue =:userId)");
	        sql.append(" or memo_user in(select fieldDataValue from oa_meeting_apply_record_scope where scopeValue =:userId)");
	        sql.append(" or attend_user in(select fieldDataValue from oa_meeting_apply_record_scope where scopeValue in(:unitorgList)))");
	        
	        sql.append(" and ((start_time between :startDateStr and :endDateStr) or (end_time between :startDateStr and :endDateStr)");
	        sql.append(" or (start_time <= :startDateStr and end_time >= :endDateStr)) ");
	        
	        paramMap.put("unitorgList", unitorgList);
	        paramMap.put("startDateStr", startDateStr);
	        paramMap.put("endDateStr", endDateStr);
	        paramMap.put("userId", userId);
	    }else if("-1".equals(type)) {
	    	sql.append(" and 1<>1 ");
	    }else {    //全部
	    	sql.append(" and ((((status ='3' and createdBy =:userId) or status in ('1','4','5'))");
	        sql.append(" and");
	        sql.append(" (emcee_user in(select fieldDataValue from oa_meeting_apply_record_scope where scopeValue =:userId)");
	        sql.append(" or memo_user in(select fieldDataValue from oa_meeting_apply_record_scope where scopeValue =:userId)");
	        sql.append(" or attend_user in(select fieldDataValue from oa_meeting_apply_record_scope where scopeValue in(:unitorgList)) "
	        		+ "or meeting_attendants in(select fieldDataValue from oa_meeting_apply_record_scope where scopeValue in(:unitorgList))))");
	        sql.append(" or (createdBy =:userId and status not in ('-1', '0', '6', '2'))) ");
	        sql.append(" and ((start_time between :startDateStr and :endDateStr) or (end_time between :startDateStr and :endDateStr)");
	        sql.append(" or (start_time <= :startDateStr and end_time >= :endDateStr)) ");
	        
	        paramMap.put("unitorgList", unitorgList);
	        paramMap.put("startDateStr", startDateStr);
	        paramMap.put("endDateStr", endDateStr);
	        paramMap.put("userId", userId);
	    }
	    sql.append(" order by start_time asc");
	    LOGGER.debug("---sql:"+sql);

	    LOGGER.debug("-startDateStr:"+paramMap.get("startDateStr"));
	    LOGGER.debug("-endDateStr:"+paramMap.get("endDateStr"));
	    LOGGER.debug("-userId:"+paramMap.get("userId"));
	    
        List<Map> arList = super.findByListNativeQuery(sql.toString(), null, paramMap);
        if(CollectionUtils.isNotEmpty(arList)){
            for(Map m : arList){
                Map<String,Object> timeUsedMap = new HashMap<String,Object>(); 
                timeUsedMap.put("title", m.get("name"));
                String start = m.get("start_time") + ":00";
                String end = m.get("end_time") + ":00";
            	timeUsedMap.put("start",start);
            	timeUsedMap.put("end",end);
                timeUsedMap.put("startTime",start);
                timeUsedMap.put("endTime",end);
                timeUsedMap.put("resourceId", m.get("boardroom_id"));
                timeUsedMap.put("color", "#FF9933");
                timeUsedMap.put("block", false);
                timeUsedMap.put("canView", true);
                timeUsedMap.put("applyrecordId", m.get("id"));
                timeUsedMap.put("meetingStatus", m.get("status"));
                listMap.add(timeUsedMap);
            }
        }
        
        LOGGER.debug("---listMap.size():"+listMap.size());
        return listMap;
    }
    
    boolean viewMeeting(Map applyRecord, Map<String, String> params){
    	String userId = params.get("userId");
    	String corpId = params.get("corpId");
    	String token = params.get("token");
    	int status = Integer.parseInt(StringUtils.null2String(applyRecord.get("status")));
    	//创建人
    	String createdBy = StringUtils.null2String(applyRecord.get("createdBy"));
    	if(createdBy.equals(userId)){
            return true;
        }
    	if(status!=0 && status!=2 && status!=3){
    		//主持人
            List<String> eScopeList = new ArrayList<>();
            eScopeList.add(StringUtils.null2String(applyRecord.get("emcee_user")));
            List<MeetingScope> emceeUserScopeList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "emcee_user", eScopeList,true);
            if(emceeUserScopeList!=null && emceeUserScopeList.size()>0){
                for(MeetingScope m : emceeUserScopeList){
                    String scopeValue = m.getScopevalue();
                    if(scopeValue.equals(userId)){
                        return true;
                    }
                }
            }
            //纪要员
            List<String> mScopeList = new ArrayList<>();
            mScopeList.add(StringUtils.null2String(applyRecord.get("memo_user")));
            List<MeetingScope> memoUserScopeList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "memo_user", mScopeList,true);
            if(memoUserScopeList!=null && memoUserScopeList.size()>0){
                for(MeetingScope m : memoUserScopeList){
                    String scopeValue = m.getScopevalue();
                    if(scopeValue.equals(userId)){
                        return true;
                    }
                }
            }
            //参会人员
            List<String> aScopeList = new ArrayList<>();
            aScopeList.add(StringUtils.null2String(applyRecord.get("attend_user")));
            List<MeetingScope> attendUserScopeList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "attend_user", aScopeList,true);
            if(attendUserScopeList!=null && attendUserScopeList.size()>0){
                List<String> unitorgList = this.orgApiService.getOrgIdsByUserIds(userId, corpId, "", "2", token);
                if(unitorgList==null){
                    unitorgList = new ArrayList<>();
                }
                unitorgList.add(userId);
                for(MeetingScope m : attendUserScopeList){
                    String scopeValue = m.getScopevalue();
                    for(String uuoStr : unitorgList){
                        if(uuoStr.equals(scopeValue)){
                            return true;
                        }
                    }
                }
            }
            //会议列席人
            List<String> atsScopeList = new ArrayList<>();
            atsScopeList.add(StringUtils.null2String(applyRecord.get("meeting_attendants")));
            List<MeetingScope> attendantsScopeList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "meeting_attendants", atsScopeList,true);
            if(attendantsScopeList!=null && attendantsScopeList.size()>0){
                List<String> unitorgList = this.orgApiService.getOrgIdsByUserIds(userId, corpId, "", "2", token);
                if(unitorgList==null){
                    unitorgList = new ArrayList<>();
                }
                unitorgList.add(userId);
                for(MeetingScope m : attendantsScopeList){
                    String scopeValue = m.getScopevalue();
                    for(String uuoStr : unitorgList){
                        if(uuoStr.equals(scopeValue)){
                            return true;
                        }
                    }
                }
            }
    	}
        return false;
    }
    
    /**
     * 预定会议日历上，获取会议室相关的数据
     * @param bsList
     * @param startDateStr
     * @return
     */
    public List<Map<String,Object>> getBoardRoomInfos(List<Map> bsList, String startDateStr) {
    	LOGGER.debug("-----getBoardRoomInfos----");
    	List<Map<String,Object>> listMap = new ArrayList<Map<String,Object>>();
    	try {
			if(bsList!=null && bsList.size()>0){
				for(Map bs : bsList){
					String boardroomSetId = StringUtils.null2String(bs.get("id"));
					String bsStartTime = StringUtils.null2String(bs.get("startTime"))+":00";
					String bsEndTime = StringUtils.null2String(bs.get("endTime"))+":59";
					
					LOGGER.debug("-bsStartTime:"+bsStartTime+"----bsEndTime:"+bsEndTime);
					
					int beforeDate = Integer.parseInt(StringUtils.null2String(bs.get("beforeDays")));
					boolean flag = true;
					if(beforeDate != 0 && StringUtils.isNotBlank(startDateStr)) {
						GregorianCalendar gc = new GregorianCalendar();
			        	gc.setTime(new Date());
			        	gc.add(Calendar.DATE, beforeDate);
			        	SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			        	Date limitDate = sf.parse(sf.format(gc.getTime()));
			        	Date startDate = sf.parse(startDateStr);
//			        	Date nowDate = sf.parse(sf.format(new Date()));
//			        	if(nowDate.getTime() > startDate.getTime() || startDate.getTime() > limitDate.getTime()) {
//			        		flag = false;
//			        	}
			        	if(limitDate.getTime()>startDate.getTime()) {
			        		flag=false;
			        	}
					}
					//会议室开始时间之前的记录
//					if(flag && !"00:00:00".equals(bsStartTime)){
					if(flag && !"00:00:00".equals(bsStartTime)){
						Map<String,Object> timeUsedStartMap = new HashMap<String,Object>(); 
						timeUsedStartMap.put("title", "");
						timeUsedStartMap.put("start","00:00:00");
						timeUsedStartMap.put("end",bsStartTime);
						timeUsedStartMap.put("resourceId", boardroomSetId);
						timeUsedStartMap.put("color", "#F2F2F2");
						timeUsedStartMap.put("editable", false);
						timeUsedStartMap.put("block", true);
						listMap.add(timeUsedStartMap);
					}
					Map<String,Object> timeUsedEndMap = new HashMap<String,Object>();
					timeUsedEndMap.put("title", "");
					timeUsedEndMap.put("resourceId", boardroomSetId);
					timeUsedEndMap.put("color", "#F2F2F2");
					timeUsedEndMap.put("editable", false);
					timeUsedEndMap.put("block", true);
//					timeUsedEndMap.put("start", bsEndTime);
					timeUsedEndMap.put("start", flag ? bsEndTime : "00:00:00");
					timeUsedEndMap.put("end","23:59:59");
					timeUsedEndMap.put("startTime", bsStartTime);
					timeUsedEndMap.put("endTime", bsEndTime);
					timeUsedEndMap.put("type", "1");
					listMap.add(timeUsedEndMap);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return listMap;
    }
    
    /**
     * 周视图，会议室带提前预定时间限制时，对日历视图不可选地方置灰
     * @param bsList
     * @param startDateStr
     * @param endDateStr
     * @return
     */
    public List<Map<String,Object>> getBoardRoomInfos(List<Map> bsList, String startDateStr, String endDateStr) {
    	List<Map<String,Object>> listMap = new ArrayList<Map<String,Object>>();
    	try {
			if(bsList!=null && bsList.size()>0){
				for(Map bs : bsList){
					String boardroomSetId = StringUtils.null2String(bs.get("id"));
					String bsStartTime = StringUtils.null2String(bs.get("startTime"))+":00";
					String bsEndTime = StringUtils.null2String(bs.get("endTime"))+":59";
					String nowDateStr = "";
					String limitDateStr = "";
					int beforeDate = Integer.parseInt(StringUtils.null2String(bs.get("beforeDays")));
					if(beforeDate != 0) {
						GregorianCalendar gc = new GregorianCalendar();
			        	gc.setTime(new Date());
			        	gc.add(Calendar.DATE, beforeDate);
			        	SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			        	nowDateStr = sf.format(new Date());
			        	Date nowDate = sf.parse(nowDateStr);
			        	limitDateStr = sf.format(gc.getTime());//可选的最后一天
			        	Date limitDate = sf.parse(limitDateStr);
			        	Date startDate = sf.parse(startDateStr);
			        	gc.setTime(sf.parse(endDateStr));
			        	gc.add(Calendar.DATE, -1);
			        	Date endDate = gc.getTime();
			        	Map<String,Object> timeUsedEndMap = new HashMap<String,Object>();
			        	timeUsedEndMap.put("title", "");
						timeUsedEndMap.put("resourceId", boardroomSetId);
						timeUsedEndMap.put("color", "#F2F2F2");
						timeUsedEndMap.put("editable", false);
						timeUsedEndMap.put("block", true);
			        	if(limitDate.getTime() <= startDate.getTime() || nowDate.getTime() >= endDate.getTime()) {
							if(limitDate.getTime() == startDate.getTime()) {
								gc.setTime(startDate);
								gc.add(Calendar.DATE, 1);
								startDateStr = sf.format(gc.getTime());
							}
							if(nowDate.getTime() == endDate.getTime()) {
								gc.setTime(endDate);
								gc.add(Calendar.DATE, -1);
								endDateStr = sf.format(gc.getTime());
							}
							timeUsedEndMap.put("start", startDateStr);
							timeUsedEndMap.put("end", endDateStr);
			        	}else if(nowDate.getTime() > startDate.getTime() && limitDate.getTime() < endDate.getTime()) {
			        		Map<String,Object> timeUsedStartMap = new HashMap<String,Object>(); 
							timeUsedStartMap.put("title", "");
							timeUsedStartMap.put("start", startDateStr);
							timeUsedStartMap.put("end",nowDateStr);
							timeUsedStartMap.put("resourceId", boardroomSetId);
							timeUsedStartMap.put("color", "#F2F2F2");
							timeUsedStartMap.put("editable", false);
							timeUsedStartMap.put("block", true);
							listMap.add(timeUsedStartMap);
							timeUsedEndMap.put("start", limitDateStr);
							timeUsedEndMap.put("end", endDateStr);
			        	}else if(nowDate.getTime() <= startDate.getTime() && startDate.getTime() < limitDate.getTime() && limitDate.getTime() < endDate.getTime()) {
							timeUsedEndMap.put("start", limitDateStr);
							timeUsedEndMap.put("end", endDateStr);
			        	}else if(startDate.getTime() < nowDate.getTime() && nowDate.getTime() < endDate.getTime() && endDate.getTime() <= limitDate.getTime()) {
							timeUsedEndMap.put("start", startDateStr);
							timeUsedEndMap.put("end", nowDateStr);
			        	}
			        	timeUsedEndMap.put("startTime", bsStartTime);
						timeUsedEndMap.put("endTime", bsEndTime);
						timeUsedEndMap.put("type", "1");
						listMap.add(timeUsedEndMap);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return listMap;
    }
    
    /**
     * 分离前的
     * @param bsList
     * @param startDateStr
     * @return
     */
    public List<Map<String,Object>> getBoardRoomInfo(List<BoardroomSet> bsList, String startDateStr) {
    	//List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
    	List<Map<String,Object>> listMap = new ArrayList<Map<String,Object>>();
    	try {
			if(bsList!=null && bsList.size()>0){
				for(BoardroomSet bs : bsList){
					//获取bsList的时候已判断过
//    			BoardroomCategorySet set = this.categoryDao.findById(bs.getCategoryId()).get();
//    			if(set == null){
//    				continue;
//    			}
					//Map<String,Object> boardroomMap = new HashMap<String,Object>(); 
					
					String boardroomSetId = bs.getId();
					String bsStartTime = bs.getStartTime()+":00";
					String bsEndTime = bs.getEndTime()+":59";
					int beforeDate = bs.getBeforeDays();
					boolean flag = true;
					if(beforeDate != 0 && StringUtils.isNotBlank(startDateStr)) {
						GregorianCalendar gc = new GregorianCalendar();
			        	gc.setTime(new Date());
			        	gc.add(Calendar.DATE, beforeDate);
			        	SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			        	Date limitDate = sf.parse(sf.format(gc.getTime()));
			        	Date startDate = sf.parse(startDateStr);
			        	Date nowDate = sf.parse(sf.format(new Date()));
			        	if(nowDate.getTime() > startDate.getTime() || startDate.getTime() > limitDate.getTime()) {
			        		flag = false;
			        	}
					}
					//会议室开始时间之前的记录
					if(flag && !"00:00:00".equals(bsStartTime)){
						Map<String,Object> timeUsedStartMap = new HashMap<String,Object>(); 
						timeUsedStartMap.put("title", "");
						timeUsedStartMap.put("start","00:00:00");
						timeUsedStartMap.put("end",bsStartTime);
						timeUsedStartMap.put("resourceId", boardroomSetId);
						timeUsedStartMap.put("color", "#F2F2F2");
						timeUsedStartMap.put("editable", false);
						timeUsedStartMap.put("block", true);
						listMap.add(timeUsedStartMap);
					}
					Map<String,Object> timeUsedEndMap = new HashMap<String,Object>();
					timeUsedEndMap.put("title", "");
					timeUsedEndMap.put("resourceId", boardroomSetId);
					timeUsedEndMap.put("color", "#F2F2F2");
					timeUsedEndMap.put("editable", false);
					timeUsedEndMap.put("block", true);
					timeUsedEndMap.put("start", flag ? bsEndTime : "00:00:00");
					timeUsedEndMap.put("end","23:59:59");
					timeUsedEndMap.put("startTime", bsStartTime);
					timeUsedEndMap.put("endTime", bsEndTime);
					timeUsedEndMap.put("type", "1");
					listMap.add(timeUsedEndMap);
					//boardroomMap.put("boardroomSet", bs);
					//boardroomMap.put("applyRecordListMap", listMap);
					//list.add(boardroomMap);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return listMap;
    }
    
    /**
     * 周视图，会议室带提前预定时间限制时，对日历视图不可选地方置灰(前后端分离前的)
     * @param bsList
     * @param startDateStr
     * @param endDateStr
     * @return
     */
    public List<Map<String,Object>> getBoardRoomInfo(List<BoardroomSet> bsList, String startDateStr, String endDateStr) {
    	List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
    	List<Map<String,Object>> listMap = new ArrayList<Map<String,Object>>();
    	try {
			if(bsList!=null && bsList.size()>0){
				for(BoardroomSet bs : bsList){
					//Map<String,Object> boardroomMap = new HashMap<String,Object>(); 
					
					String boardroomSetId = bs.getId();
					String bsStartTime = bs.getStartTime()+":00";
					String bsEndTime = bs.getEndTime()+":59";
					String nowDateStr = "";
					String limitDateStr = "";
					int beforeDate = bs.getBeforeDays();
					if(beforeDate != 0) {
						GregorianCalendar gc = new GregorianCalendar();
			        	gc.setTime(new Date());
			        	gc.add(Calendar.DATE, beforeDate);
			        	SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			        	nowDateStr = sf.format(new Date());
			        	Date nowDate = sf.parse(nowDateStr);
			        	limitDateStr = sf.format(gc.getTime());//可选的最后一天
			        	Date limitDate = sf.parse(limitDateStr);
			        	Date startDate = sf.parse(startDateStr);
			        	gc.setTime(sf.parse(endDateStr));
			        	gc.add(Calendar.DATE, -1);
			        	Date endDate = gc.getTime();
			        	Map<String,Object> timeUsedEndMap = new HashMap<String,Object>();
			        	timeUsedEndMap.put("title", "");
						timeUsedEndMap.put("resourceId", boardroomSetId);
						timeUsedEndMap.put("color", "#F2F2F2");
						timeUsedEndMap.put("editable", false);
						timeUsedEndMap.put("block", true);
			        	if(limitDate.getTime() <= startDate.getTime() || nowDate.getTime() >= endDate.getTime()) {
							if(limitDate.getTime() == startDate.getTime()) {
								gc.setTime(startDate);
								gc.add(Calendar.DATE, 1);
								startDateStr = sf.format(gc.getTime());
							}
							if(nowDate.getTime() == endDate.getTime()) {
								gc.setTime(endDate);
								gc.add(Calendar.DATE, -1);
								endDateStr = sf.format(gc.getTime());
							}
							timeUsedEndMap.put("start", startDateStr);
							timeUsedEndMap.put("end", endDateStr);
			        	}else if(nowDate.getTime() > startDate.getTime() && limitDate.getTime() < endDate.getTime()) {
			        		Map<String,Object> timeUsedStartMap = new HashMap<String,Object>(); 
							timeUsedStartMap.put("title", "");
							timeUsedStartMap.put("start", startDateStr);
							timeUsedStartMap.put("end",nowDateStr);
							timeUsedStartMap.put("resourceId", boardroomSetId);
							timeUsedStartMap.put("color", "#F2F2F2");
							timeUsedStartMap.put("editable", false);
							timeUsedStartMap.put("block", true);
							listMap.add(timeUsedStartMap);
							timeUsedEndMap.put("start", limitDateStr);
							timeUsedEndMap.put("end", endDateStr);
			        	}else if(nowDate.getTime() <= startDate.getTime() && startDate.getTime() < limitDate.getTime() && limitDate.getTime() < endDate.getTime()) {
							timeUsedEndMap.put("start", limitDateStr);
							timeUsedEndMap.put("end", endDateStr);
			        	}else if(startDate.getTime() < nowDate.getTime() && nowDate.getTime() < endDate.getTime() && endDate.getTime() <= limitDate.getTime()) {
							timeUsedEndMap.put("start", startDateStr);
							timeUsedEndMap.put("end", nowDateStr);
			        	}
			        	timeUsedEndMap.put("startTime", bsStartTime);
						timeUsedEndMap.put("endTime", bsEndTime);
						timeUsedEndMap.put("type", "1");
						listMap.add(timeUsedEndMap);
//						boardroomMap.put("boardroomSet", bs);
//						boardroomMap.put("applyRecordListMap", listMap);
//						list.add(boardroomMap);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return listMap;
    }
    
    public List<Map<String,Object>> getApplyRecordView(List<BoardroomSet> bsList,String startDate) {
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        if(bsList!=null && bsList.size()>0){
            for(BoardroomSet bs : bsList){
            	BoardroomCategorySet set = this.categoryDao.findById(bs.getCategoryId()).get();
            	if(set == null){
            		continue;
            	}
                String boardroomSetId = bs.getId();
                String bsStartTime = startDate + " " + bs.getStartTime()+":00";
                String bsEnd = bs.getEndTime();
                if("24:00".equals(bsEnd)){
                	bsEnd = "23:59";
                }
    			String bsEndTime = startDate + " " + bsEnd +":59";
    			Date boardStart = DateUtils.parseTime(bsStartTime);
                Date boardEnd = DateUtils.parseTime(bsEndTime);
    			
                String startDateStr = startDate + " 00:00:00";
                String endDateStr = startDate + " 23:59:59";
                List<ApplyRecord> arList = this.dao.getApplyRecordList(boardroomSetId,startDateStr,endDateStr);
                if(arList!=null && arList.size()>0){
                    int len = arList.size();
                    for(int i=0;i<len;i++){
                        ApplyRecord applyRecord = arList.get(i);
                        Map<String,Object> timeUsedMap = new HashMap<String,Object>(); 
                        timeUsedMap.put("title", "");
                        String start = applyRecord.getStartTime()+":00";
                        String end = applyRecord.getEndTime()+":00";
                        Date meetingStart = DateUtils.parseTime(start);
                        Date meetingEnd = DateUtils.parseTime(end);
                        if(meetingStart.getTime()<boardStart.getTime()){
                        	timeUsedMap.put("start",bsStartTime);
                        }else{
                        	timeUsedMap.put("start",start);
                        }
                        if(meetingEnd.getTime() > boardEnd.getTime()){
                        	timeUsedMap.put("end",bsEndTime);
                        }else{
                        	timeUsedMap.put("end",end);
                        }
                        timeUsedMap.put("resourceId", applyRecord.getBoardroomId());
                        timeUsedMap.put("color", "#FF9933");
                        timeUsedMap.put("editable", false);
                        timeUsedMap.put("block", true);
                        list.add(timeUsedMap);
                    }
                }
            }
        }
        
        return list;
    }

    public List<String> getWeekdayDateStr(String dateStr) {
        List<String> list = new ArrayList<String>();
        Calendar cal = Calendar.getInstance();  
        cal.setTime(DateUtils.parseDate(dateStr));
        int d = 0;  
        if(cal.get(Calendar.DAY_OF_WEEK)==1){  
            d = -6;  
        }else{  
            d = 2-cal.get(Calendar.DAY_OF_WEEK);  
        }  
        cal.add(Calendar.DAY_OF_WEEK, d);  
        //所在周第一天日期  
        list.add(DateUtils.formatDate(cal.getTime()));
        //所在周第二天日期  
        cal.add(Calendar.DAY_OF_WEEK, 1);  
        list.add(DateUtils.formatDate(cal.getTime()));
        //所在周第三天日期  
        cal.add(Calendar.DAY_OF_WEEK, 1);  
        list.add(DateUtils.formatDate(cal.getTime()));
        //所在周第四天日期  
        cal.add(Calendar.DAY_OF_WEEK, 1);  
        list.add(DateUtils.formatDate(cal.getTime()));
        //所在周第五天日期  
        cal.add(Calendar.DAY_OF_WEEK, 1);  
        list.add(DateUtils.formatDate(cal.getTime()));
        //所在周第六天日期  
        cal.add(Calendar.DAY_OF_WEEK, 1);  
        list.add(DateUtils.formatDate(cal.getTime()));
        //所在周第七天日期  
        cal.add(Calendar.DAY_OF_WEEK, 1);  
        list.add(DateUtils.formatDate(cal.getTime()));

        return list;
    }

    /**
     * 保存验证
     * @param id
     * @param checkdata
     * @param type
     * @param corpId
     * @return
     */
    public String checkApplyRecordInfo(String id, String checkdata, int type, String corpId) {
        String msg = "";
        List<ApplyRecord> list = new ArrayList<ApplyRecord>();
        if (type == 1) {// 验证名称
            if (StringUtils.isNotEmpty(id)) {// 编辑
                list = this.dao.getApplyRecordByName(id, checkdata, corpId);
            } else {// 新建
                list = this.dao.getApplyRecordByName(checkdata, corpId);
            }
        }
        if (list != null && list.size() > 0) {
            msg = this.getCheckMsgStr(type);
        }
        return msg;
    }
    
    
    /**
     * 验证报错返回msg信息
     * 
     * @param type
     * @return
     */
    private String getCheckMsgStr(int type) {
        String msg = "";
        switch (type) {
        case 1:
            msg = "您输入的会议名称已存在";
            break;
        case 2:
            msg = "会议时间段内已有其他会议";
            break;
        case 3:
            msg = "所选时间段内会议室已被占用，请重新选择";
            break;
        }
        return msg;
    }

    /**
     * 验证会议时间段
     * @param id
     * @param startTime
     * @param endTime
     * @param boardroomId
     * @param corpId
     * @return
     */
    public String checkApplyRecordDate(String id, String startTime, String endTime, String boardroomId, String corpId) {
        String msg = "";
        List<ApplyRecord> list = new ArrayList<ApplyRecord>();
        if (StringUtils.isNotEmpty(id)) {// 编辑
            list = this.dao.getApplyRecordSeDate(id, startTime,endTime,corpId,boardroomId);
        } else {// 新建
            list = this.dao.getApplyRecordSeDate(startTime,endTime,corpId,boardroomId);
        }
        if (list != null && list.size() > 0) {
            msg = this.getCheckMsgStr(2);
        }
        return msg;
    }
    
    /**
     * 查询会议室下的所有会议
     * 
     */
    public List<ApplyRecord> getApplyRecordList(List<String> boardroomIdList){
    	return this.dao.getApplyRecordList(boardroomIdList);
    }

    /**
     * 根据会议id改变会议状态
     * @param status
     * @param ids
     * @return
     */
    public int changeStatusById(int status, List<String> ids){
        return this.dao.updApplyRecord(status, ids);
    }
    
    /**
     * 根据条件查询会议信息，供日程使用
     * @param title
     * @param startTime
     * @param endTime
     * @param corpId
     * @param userId
     * @return
     */
	public List<Map> queryApplyRecordList(String title, String startTime, String endTime, String corpId, String userId, String token){
		LOGGER.info("----queryApplyRecordList----");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT omar.id,omar.name,omar.start_time startTime,omar.end_time endTime,omar.createdBy createdUserId,omar.status,omar.createdDate");
		sql.append("	FROM oa_meeting_apply_record omar");
		sql.append("	left join oa_meeting_notice_info info on omar.id = info.apply_record_id ");
		sql.append(" WHERE omar.corp_id = :corpId AND omar.is_sync=1");
		sql.append("	AND ((omar.status IN ('3') AND omar.createdBy = :userId) OR omar.status IN ('1','4','5')) ");
//		sql.append("	AND (omar.emcee_user IN (:emceeScopeList)");
//		sql.append("		 OR omar.memo_user IN (:memoScopeList)");
//		sql.append("		 OR omar.attend_user IN (:attendScopeList))");
		sql.append("	AND (info.status=2 or (info.status!=3 and omar.is_sync_calendar=1))AND (info.notice_user_id= :userId or info.receive_user_id = :userId)");
		if(StringUtils.isNotEmpty(startTime)){
			sql.append("	AND ((omar.start_time >= :startTime AND omar.start_time <= :endTime) OR (omar.end_time >= :startTime AND omar.end_time <= :endTime))");
			paramMap.put("startTime", startTime);
			paramMap.put("endTime", endTime);
		}
//		if(StringUtils.isNotEmpty(endTime)){
//			sql.append("	AND omar.end_time <= :endTime");
//			paramMap.put("endTime", endTime);
//		}
		if(StringUtils.isNotEmpty(title)){
			sql.append("	AND omar.name like :title");
			paramMap.put("title", "%" + title + "%");
		}
		sql.append(" AND omar.id not in (SELECT calendarId from oa_calendar_finished WHERE partId=:userId)");
		sql.append(" ORDER BY omar.start_time desc");
		List<String> list = null;
		if(StringUtils.isNotEmpty(token)) {
			list = orgApiService.getOrgIdsByUserIds(userId,corpId,"","2",token);
		}else {
			list = new ArrayList<String>();
		}
		list.add(userId);
		paramMap.put("corpId", corpId);
//		List<String> emceeScopeList = popScopeService.getFieldDataValue("oa_meeting_apply_record_scope", list, "oa_meeting_apply_record", "emcee_user");
//		if(emceeScopeList == null) emceeScopeList = new ArrayList<String>();
//		List<String> memoScopeList = popScopeService.getFieldDataValue("oa_meeting_apply_record_scope", list, "oa_meeting_apply_record", "memo_user");
//		if(memoScopeList == null) memoScopeList = new ArrayList<String>();
//		List<String> attendScopeList = popScopeService.getFieldDataValue("oa_meeting_apply_record_scope", list, "oa_meeting_apply_record", "attend_user");
//		if(attendScopeList == null) attendScopeList = new ArrayList<String>();
//		paramMap.put("emceeScopeList", emceeScopeList.size() > 0 ? emceeScopeList : "");
//		paramMap.put("memoScopeList", memoScopeList.size() > 0 ? memoScopeList : "");
//		paramMap.put("attendScopeList", attendScopeList.size() > 0 ? attendScopeList : "");
		paramMap.put("userId", userId);
		paramMap.put("corpId", corpId);
		
		LOGGER.info("--sql："+sql);
		
		return super.findByListNativeQuery(sql.toString(), null, paramMap);
	}
	
	/**
	 * 根据会议类型id查询
	 * @param meetingTypeId
	 * @param corpId
	 * @return
	 */
	public List<Map> getApplyRecordsByMeetingTypeId(String... meetingTypeIds){
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append("select id from oa_meeting_apply_record where meeting_type_id in (:meetingTypeIds)");
		paramMap.put("meetingTypeIds", Arrays.asList(meetingTypeIds));
		return super.findByListNativeQuery(sql.toString(), null, paramMap);
	}
	
	/**
	 * 检测该会议室再周期内是否被占用
	 * @param entity
	 * @param corpId
	 * @return
	 */
	public String checkCycleApplyRecordDate(ApplyRecord entity, List<Map<String, String>> cyclelist, String corpId) {
		String msg = "";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append("select start_time, end_time from oa_meeting_apply_record ");
		sql.append(" where boardroom_id=:boardroomId and status in (1,4) and corp_Id=:corpId ");
		sql.append(" order by start_time");
		paramMap.put("boardroomId", entity.getBoardroomId());
		paramMap.put("corpId", corpId);
		List<Map> meetinglist = super.findByListNativeQuery(sql.toString(), null, paramMap);
		String starTime = entity.getStartTime().substring(10, 16);
		String endTime = entity.getEndTime().substring(10, 16);
		if(CollectionUtils.isNotEmpty(meetinglist) && CollectionUtils.isNotEmpty(cyclelist)) {
			for(Map m2 : meetinglist) {
				long startDateLong2 = String2Date((String)m2.get("start_time")).getTime();
				long endDateLong2 = String2Date((String)m2.get("end_time")).getTime();
				for(Map<String, String> m : cyclelist) {
					long startDateLong = String2Date(m.get("startDate") + starTime).getTime();
					long endDateLong = String2Date(m.get("endDate") + endTime).getTime();
					if((startDateLong >= startDateLong2 && startDateLong < endDateLong2) || (endDateLong > startDateLong2 && endDateLong <= endDateLong2)
							|| (startDateLong <= startDateLong2 && endDateLong >= endDateLong2) || (startDateLong >= startDateLong2 && endDateLong <= endDateLong2)) {
						msg = this.getCheckMsgStr(3);
						break;
					}
				}
			}
		}
		return msg;
	}
	
	private Date String2Date(String date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); 
        try {
        	if(StringUtils.isNotEmpty(date))
            return simpleDateFormat.parse(date);
        } catch(Exception px) {
            px.printStackTrace();
        }
        return null;
    }
	
	/**
	 * 获取周期每次的会议时间
	 * @param entity
	 * @return
	 */
	public List<Map<String, String>> getCycleDateList(ApplyRecord entity){
		int type = entity.getCycleType();
		String startDate = entity.getStartTime().substring(0, 10);
		String endDate = entity.getEndTime().substring(0, 10);
		String cycleEndDate = entity.getCycleEndTime();
		String cycleValue = entity.getCycleValue();
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		if(type == 0) {
			list = getCycleMeetingDatesByDayType(startDate, endDate, cycleEndDate, cycleValue);
		}else if(type == 1) {
			list = getCycleMeetingDatesByWeekType(startDate, endDate, cycleEndDate, cycleValue);
		}else if(type == 2) {
			list = getCycleMeetingDatesByMonthType(startDate, endDate, cycleEndDate, cycleValue);
		}
		return list;
	}
	
	public List<ApplyRecord> saveCycleMeeting(ApplyRecord entity, List<Map<String, String>> list) {
		return saveCycleMeeting(entity, list, false);
	}
	
	/**
	 * 保存周期会议
	 * @param entity
	 */
	public List<ApplyRecord> saveCycleMeeting(ApplyRecord entity, List<Map<String, String>> list, boolean onlyBoardRoom) {
		String starTime = entity.getStartTime().substring(10, 16);
		String endTime = entity.getEndTime().substring(10, 16);
		List<ApplyRecord> entityList = new ArrayList<ApplyRecord>();
		ApplyRecord ar = null;
		List<MeetingScope> newScopeList = new ArrayList<MeetingScope>();
		String cycleId = UuidUtils.UUID();
		for(Map<String, String> map : list) {
			ar = applyRecordCopy(entity);
			ar.setStartTime(map.get("startDate") + starTime);
			ar.setEndTime(map.get("endDate") + endTime);
			ar.setCycleId(cycleId);
			if(!onlyBoardRoom) {
				ar.setEmceeUser(makeMeetingScope(entity.getEmceeUser(), newScopeList));
		    	ar.setMemoUser(makeMeetingScope(entity.getMemoUser(), newScopeList));
		    	ar.setAttendUser(makeMeetingScope(entity.getAttendUser(), newScopeList));
		    	ar.setMeetingAttendants(makeMeetingScope(entity.getMeetingAttendants(), newScopeList));
		    	ar.setBusinessRecordId(entity.getBusinessRecordId());
		    	ar.setMeetingPeopleNum(entity.getMeetingPeopleNum());
		    	ar.setMeetingServe(entity.getMeetingServe());
			}
			entityList.add(ar);
		}
		dao.updateCycleId(entity.getId(), cycleId);
		meetingScopeService.save(newScopeList);
		return this.save(entityList);
	}    
	
	/**
	 * 每个周期会议的参会人员都要新建一份，因为有转本部门的功能
	 * @param fielddatavalue
	 * @param newScopeList
	 * @return
	 */
	private String makeMeetingScope(String fielddatavalue, List<MeetingScope> newScopeList) {
		if(StringUtils.isNotEmpty(fielddatavalue)) {
			List<MeetingScope> scopeList = meetingScopeService.getMeetingScopeList(fielddatavalue);
			String newId = UuidUtils.UUID();
			if(CollectionUtils.isNotEmpty(scopeList)) {
				MeetingScope newScope = null;
				for(MeetingScope ms : scopeList) {
					newScope = meetingScopeCopy(ms, newId);
					newScopeList.add(newScope);
				}
			}
			return newId;
		}
		return null;
	}
	
	private MeetingScope meetingScopeCopy(MeetingScope ms, String fielddatavalue) {
		MeetingScope newScope = new MeetingScope();
		newScope.setScopetype(ms.getScopetype());
		newScope.setType(ms.getType());
		newScope.setScopevalue(ms.getScopevalue());
		newScope.setName(ms.getName());
		newScope.setFielddatatable(ms.getFielddatatable());
		newScope.setFielddatavalue(fielddatavalue);
		newScope.setFielddata(ms.getFielddata());
		newScope.setDeleteflag(ms.getDeleteflag());
		newScope.setSortNo(ms.getSortNo());
		return newScope;
	}
    
    /**
     * 获取本次所有周期会议日期（按周）
     * @param startTime 会议开始日期
     * @param endTime 会议结束日期
     * @param cycleEndDate 周期截止日期
     * @param param 星期几（多日用逗号间隔）
     * @return
     */
    public List<Map<String, String>> getCycleMeetingDatesByWeekType(String startTime, String endTime, String cycleEndDate, String param) {
    	List<Map<String, String>> result = new ArrayList<Map<String, String>>(); 
    	try {
    		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
    		Date _startTime = sf.parse(startTime);
        	Date _endTime = sf.parse(endTime);
        	Date _cycleEndDate = sf.parse(cycleEndDate);
        	//如果会议跨天，differenceDay存储跨了多少天
        	String differenceDay = (_endTime.getTime() - _startTime.getTime()) / (24 * 60 * 60 * 1000) + "";
        	GregorianCalendar gc = new GregorianCalendar();
        	gc.set(gc.get(Calendar.YEAR),gc.get(Calendar.MONTH),gc.get(Calendar.DATE));
        	gc.setTime(_endTime);
        	while(_startTime.getTime() < _cycleEndDate.getTime()) {
        		gc.add(Calendar.DATE, 1);
        		_startTime = gc.getTime();
        		gc.setTime(_startTime);
        		if(param.contains(gc.get(Calendar.DAY_OF_WEEK) + "")) {
        			Map<String, String> map = new HashMap<String, String>();
        			gc.add(Calendar.DATE, Integer.parseInt(differenceDay));
            		_endTime = gc.getTime();
		    		map.put("startDate", sf.format(_startTime));
		    		map.put("endDate", sf.format(_endTime));
		    		result.add(map);
        		}
        	}
    	} catch (Exception e) {
			e.printStackTrace();
		}
    	return result;
    }
    
    /**
     * 获取本次所有周期会议日期（按天）
     * @param startTime 会议开始日期
     * @param endTime 会议结束日期
     * @param cycleEndDate 周期截止日期
     * @param dayNum 周期天数
     * @return
     */
    public List<Map<String, String>> getCycleMeetingDatesByDayType(String startTime, String endTime, String cycleEndDate, String dayNum){
    	List<Map<String, String>> result = new ArrayList<Map<String, String>>(); 
    	try {
        	SimpleDateFormat sf  = new SimpleDateFormat("yyyy-MM-dd");
	    	Date _startTime = sf.parse(startTime);
        	Date _endTime = sf.parse(endTime);
        	Date _cycleEndDate = sf.parse(cycleEndDate);
        	//如果会议跨天，differenceDay存储跨了多少天
        	String differenceDay = (_endTime.getTime() - _startTime.getTime()) / (24 * 60 * 60 * 1000) + "";
        	GregorianCalendar gc = new GregorianCalendar();
        	gc.set(gc.get(Calendar.YEAR),gc.get(Calendar.MONTH),gc.get(Calendar.DATE));
        	long nextMeetingStartDate = 0L;
        	Map<String, String> map = null;
        	while(nextMeetingStartDate <= _cycleEndDate.getTime()){
        		if(map != null) result.add(map);
        		map = new HashMap<String, String>();
        		//计算下次会议的开始时间
        		gc.setTime(_endTime);
            	gc.add(Calendar.DATE, Integer.parseInt(dayNum) + 1);
            	_startTime = gc.getTime();
            	map.put("startDate", sf.format(_startTime));
            	nextMeetingStartDate = _startTime.getTime();
            	//计算下次会议的结束时间
            	gc.setTime(_startTime);
            	gc.add(Calendar.DATE, Integer.parseInt(differenceDay));
            	_endTime = gc.getTime();
            	map.put("endDate", sf.format(_endTime));
        	}
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return result;
    }
    
    /**
     * 获取本次所有周期会议日期（按月）
     * @param startTime 会议开始日期
     * @param endTime 会议结束日期
     * @param cycleEndDate 周期截止日期
     * @param date 每月几号
     * @return
     */
    public List<Map<String, String>> getCycleMeetingDatesByMonthType(String startTime, String endTime, String cycleEndDate, String date){
    	List<Map<String, String>> result = new ArrayList<Map<String, String>>(); 
    	try {
	    	SimpleDateFormat sf  = new SimpleDateFormat("yyyy-MM-dd");
	    	Date _startTime = sf.parse(startTime);
	    	Date _endTime = sf.parse(endTime);
	    	Date _cycleEndDate = sf.parse(cycleEndDate);
	    	//如果会议跨天，differenceDay存储跨了多少天
        	String differenceDay = (_endTime.getTime() - _startTime.getTime()) / (24 * 60 * 60 * 1000) + "";
        	GregorianCalendar gc = new GregorianCalendar();
        	gc.set(gc.get(Calendar.YEAR),gc.get(Calendar.MONTH),gc.get(Calendar.DATE));
        	gc.setTime(_endTime);
	    	int endTimeYear = gc.get(Calendar.YEAR);
	    	int endTimeMonth = gc.get(Calendar.MONTH) + 1;
	    	int endTimeDay = gc.get(Calendar.DATE);
        	int day = Integer.parseInt(date);
        	int dayOfMonth = gc.getActualMaximum(Calendar.DAY_OF_MONTH);
        	Date newStartTime = null;
        	if(day > endTimeDay) { 
        		if(day > dayOfMonth) day = dayOfMonth;
        		newStartTime = sf.parse(endTimeYear + "-" + numberLessThenTen(endTimeMonth) + "-" + day);
        	}else {
        		gc.add(Calendar.MONTH, 1);
        		dayOfMonth = gc.getActualMaximum(Calendar.DAY_OF_MONTH);
        		if(day > dayOfMonth) day = dayOfMonth;
        		newStartTime = sf.parse(gc.get(Calendar.YEAR) + "-" + numberLessThenTen(gc.get(Calendar.MONTH) + 1) + "-" + day);
        	}
    		while(newStartTime.getTime() <= _cycleEndDate.getTime()) {
	    		Map<String, String> map = new HashMap<String, String>();
	    		gc.setTime(newStartTime);
            	gc.add(Calendar.DATE, Integer.parseInt(differenceDay));
	    		map.put("startDate", sf.format(newStartTime));
	    		map.put("endDate", sf.format(gc.getTime()));
	    		result.add(map);
	    		gc.add(Calendar.MONTH, 1);
	    		day = Integer.parseInt(date);
	    		dayOfMonth = gc.getActualMaximum(Calendar.DAY_OF_MONTH);
        		if(day > dayOfMonth) day = dayOfMonth;
        		newStartTime = sf.parse(gc.get(Calendar.YEAR) + "-" + numberLessThenTen(gc.get(Calendar.MONTH) + 1) + "-" + day);
	    	}
    	} catch (Exception e) {
			e.printStackTrace();
		}
    	return result;
    }
    
    /**
     * 个位数前加个0
     * @param num
     * @return
     */
    private String numberLessThenTen(int num) {
    	return (num < 10 && num > 0) ? ("0" + num) : ("" + num);
    }
    
    private ApplyRecord applyRecordCopy(ApplyRecord entity) {
    	ApplyRecord ar = new ApplyRecord();
    	ar.setCreatedBy(entity.getCreatedBy());
    	ar.setName(entity.getName());
    	ar.setContent(entity.getContent());
//    	ar.setStartTime(entity.getStartTime());
//    	ar.setEndTime(entity.getEndTime());
    	ar.setIsCycle(entity.getIsCycle());
    	ar.setCycleType(entity.getCycleType());
    	ar.setCycleValue(entity.getCycleValue());
    	ar.setCycleEndTime(entity.getCycleEndTime());
//    	ar.setCycleId(entity.getCycleId());
    	ar.setBoardroomId(entity.getBoardroomId());
    	ar.setMeetingTypeId(entity.getMeetingTypeId());
//    	ar.setEmceeUser(entity.getEmceeUser());
//    	ar.setMemoUser(entity.getMemoUser());
//    	ar.setAttendUser(entity.getAttendUser());
    	ar.setIsNotice(entity.getIsNotice());
    	ar.setNoticeType(entity.getNoticeType());
    	ar.setNoticeTime(entity.getNoticeTime());
    	ar.setIsSigned(entity.getIsSigned());
    	ar.setSignedTime(entity.getSignedTime());
    	ar.setMeetingServe(entity.getMeetingServe());
    	ar.setStatus(entity.getStatus());
    	ar.setReason(entity.getReason());
    	ar.setQrcodeAttach(entity.getQrcodeAttach());
    	ar.setSignedType(entity.getSignedType());
    	ar.setSignedRange(entity.getSignedRange());
    	ar.setMessagePush(entity.getMessagePush());
    	ar.setRemark(entity.getRemark());
    	ar.setFileId(entity.getFileId());
    	ar.setIsSync(entity.getIsSync());
    	ar.setMeetingWay(entity.getMeetingWay());
    	ar.setAddress(entity.getAddress());
    	return ar;
    }
	
    /**
     * 查询周期会议id
     * @param ids
     * @return
     */
    public List<String> getCycleMeetingids(List<String> ids){
    	return dao.getCycleMeetingids(ids);
    }
    
    public List<ApplyRecord> getApplyRecordListByCycleId(String cycleId, String corpId){
    	return dao.getApplyRecordListByCycleId(cycleId, corpId);
    }
    
    /**
	 * 获取附件信息
	 * 
	 * @param attachmentId
	 * @param token
	 * @return
	 */
	public String getAttachmentName(String attachmentId) {
		if (StringUtils.isNotEmpty(attachmentId)) {
			return "[" + this.attachmentUtilsService.getAttachmentInfo(attachmentId, this.getToken()) + "]";
		}
		return "";
	}
	
	/**
	 * 根据fieldDataValue和fieldData，查询name
	 * @param fieldDataValue
	 * @param fieldData
	 * @return
	 */
	public String getScopeName(String fieldDataTable, String fieldDataValue, String fieldData) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append(" select name from oa_meeting_apply_record_scope where fieldDataTable=:fieldDataTable and fieldDataValue=:fieldDataValue and fieldData=:fieldData order by sort_no asc");
		paramMap.put("fieldDataTable", fieldDataTable);
		paramMap.put("fieldDataValue", fieldDataValue);
		paramMap.put("fieldData", fieldData);
		List<Map> list = super.findByListNativeQuery(sql.toString(), "",paramMap);
		String result = "";
		if(CollectionUtils.isNotEmpty(list)) {
			for(int i = 0; i < list.size(); i++) {
				if(i == list.size() - 1) result += list.get(i).get("name");
				else result += list.get(i).get("name") + ",";
			}
		}
		return result;
	}
	
	/**
	 * 根据用户id查询用户名
	 * @param userId
	 * @return
	 */
	public String getUserNameById(String userId) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append(" select user_name from sys_user where id=:id");
		paramMap.put("id", userId);
		List<Map> list = super.findByListNativeQuery(sql.toString(), "",paramMap);
		String result = "";
		if(CollectionUtils.isNotEmpty(list)) {
			result = StringUtils.null2String(list.get(0).get("user_name"));
		}
		return result;
	}
	
	/**
	 * 根据fieldDataValue和fieldData，查询name,scopeValue
	 * @param fieldDataValue
	 * @param fieldData
	 * @return
	 */
	public List<Map> getScopeValues(String fieldDataTable, String fieldDataValue, String fieldData) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append(" select scopeValue value, name text from oa_meeting_apply_record_scope where fieldDataTable=:fieldDataTable and fieldDataValue=:fieldDataValue and fieldData=:fieldData order by name desc");
		paramMap.put("fieldDataTable", fieldDataTable);
		paramMap.put("fieldDataValue", fieldDataValue);
		paramMap.put("fieldData", fieldData);
		return super.findByListNativeQuery(sql.toString(), "",paramMap);
	}
	
	/**
	 * 查询可以使用的会议室列表数据(分页)
	 * @param request
	 * @return
	 */
	public Page findCanUseBoardroomListByPage(Pageable pageable, String corpId, String userId, String boardroomName, 
			String startTime, String endTime, String categoryId, String isCycle) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append("select omar.id, ombs.id boardroomId, ombs.name boardRoomName, ombc.name boardroomCateName, omar.start_time, omar.end_time,");
		sql.append(" ombs.address, omar.is_sync boardroomStatus, ombc.id cateId, omar.cycle_id cycleId");
		sql.append(" from oa_meeting_apply_record omar");
//		if(StringUtils.isNotBlank(isCycle)) {
//			sql.append(" join (select min( start_time ) start_time, cycle_id FROM oa_meeting_apply_record ");
//			sql.append(" where is_cycle = 1 and cycle_id is not null group by cycle_id) t on omar.cycle_id=t.cycle_id and omar.start_time=t.start_time");
//		}
		sql.append(" left join oa_meeting_boardroom_set ombs on omar.boardroom_id=ombs.id");
		sql.append(" left join oa_meeting_boardroom_cate ombc on ombs.category_id=ombc.id");
		sql.append(" where omar.corp_id=:corpId and omar.createdBy=:userId and omar.is_sync=0 and omar.status=1 ");
		sql.append(" and omar.start_time > :now");
		paramMap.put("now", DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm"));
		if(StringUtils.isNotBlank(isCycle)) {
			sql.append(" and omar.is_cycle = 1 and omar.cycle_id is not null");
		}
		if(StringUtils.isNotBlank(boardroomName)) {
			sql.append(" and ombs.name like :boardroomName");
			paramMap.put("boardroomName", "%"+ boardroomName +"%");
		}
		if(StringUtils.isNotBlank(startTime)){
            sql.append(" and omar.start_time >= :startTime");
            paramMap.put("startTime", startTime + " 00:00");
        }
        if(StringUtils.isNotBlank(endTime)){
            sql.append(" and omar.end_time <= :endTime");
            paramMap.put("endTime", endTime + " 59:59");
        }
		if(StringUtils.isNotBlank(categoryId)) {
			sql.append(" and ombc.id = :categoryId");
			paramMap.put("categoryId", categoryId);
		}
		sql.append(" order by omar.createdDate desc");
		paramMap.put("corpId", corpId);
		paramMap.put("userId", userId);
		return super.findByPageNativeSQL(pageable, sql.toString(), paramMap);
	}
	

    /**
     * 取消会议后新建当前会议室申请，充当释放
     * @param entity
     */
    public void saveNewBoardRoomApply(ApplyRecord entity) {
    	ApplyRecord newEntity = new ApplyRecord();
    	newEntity.setIsSync(0);
    	newEntity.setStatus(1);
    	newEntity.setBoardroomId(entity.getBoardroomId());
    	newEntity.setStartTime(entity.getStartTime());
    	newEntity.setEndTime(entity.getEndTime());
    	newEntity.setMeetingServe(entity.getMeetingServe());
    	this.save(newEntity);
    }
	
	/**
	 * 查询已申请会议室列表数据(分页)
	 * @param request
	 * @return
	 */
	public Page findApplyBoardroomListByPage(Pageable pageable, String corpId, String userId, String boardroomName, 
			String startTime, String endTime, String categoryId, String boardroomStatus) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append("select omar.id, ombs.id boardroomId, ombs.name boardRoomName, ombc.name boardroomCateName, omar.start_time, omar.end_time,");
		sql.append(" ombs.address, omar.is_sync boardroomStatus, ombc.id cateId");
		sql.append(" from oa_meeting_apply_record omar,oa_meeting_boardroom_set ombs,oa_meeting_boardroom_cate ombc");
		sql.append(" where omar.boardroom_id=ombs.id and ombs.category_id=ombc.id and omar.corp_id=:corpId and omar.createdBy=:userId");
		sql.append(" and omar.status in (1,3,4,5)");
		if(StringUtils.isNotBlank(boardroomName)) {
			sql.append(" and ombs.name like :boardroomName");
			paramMap.put("boardroomName", "%"+ boardroomName +"%");
		}
		if(StringUtils.isNotBlank(startTime)){
            sql.append(" and omar.start_time >= :startTime");
            paramMap.put("startTime", startTime + " 00:00");
        }
        if(StringUtils.isNotBlank(endTime)){
            sql.append(" and omar.end_time <= :endTime");
            paramMap.put("endTime", endTime + " 59:59");
        }
		if(StringUtils.isNotBlank(categoryId)) {
			sql.append(" and ombc.id = :categoryId");
			paramMap.put("categoryId", categoryId);
		}
		if(StringUtils.isNotBlank(boardroomStatus)) {
			sql.append(" and omar.is_sync = :boardroomStatus");
			paramMap.put("boardroomStatus", boardroomStatus);
		}
		sql.append(" order by omar.createdDate desc , omar.start_time desc");
		paramMap.put("corpId", corpId);
		paramMap.put("userId", userId);
		return super.findByPageNativeSQL(pageable, sql.toString(), paramMap);
	}
	
	
    public void applyRecordCopy(ApplyRecord ar, ApplyRecord entity) {
    	ar.setName(entity.getName());
    	ar.setContent(entity.getContent());
    	ar.setMeetingTypeId(entity.getMeetingTypeId());
    	ar.setEmceeUser(entity.getEmceeUser());
    	ar.setMemoUser(entity.getMemoUser());
    	ar.setAttendUser(entity.getAttendUser());
    	ar.setIsNotice(entity.getIsNotice());
    	ar.setNoticeType(entity.getNoticeType());
    	ar.setNoticeTime(entity.getNoticeTime());
    	ar.setIsSigned(entity.getIsSigned());
    	ar.setSignedTime(entity.getSignedTime());
    	ar.setStatus(entity.getStatus());
    	ar.setReason(entity.getReason());
    	ar.setQrcodeAttach(entity.getQrcodeAttach());
    	ar.setSignedType(entity.getSignedType());
    	ar.setSignedRange(entity.getSignedRange());
    	ar.setMessagePush(entity.getMessagePush());
    	ar.setRemark(entity.getRemark());
    	ar.setFileId(entity.getFileId());
    	ar.setIsSync(entity.getIsSync());
    	ar.setMeetingWay(entity.getMeetingWay());
    	ar.setAddress(entity.getAddress());
    }
    
    /**
     * 新增参会人员
     * @param ar
     * @param userList
     * @param corpId
     * @param token
     */
    public void addAttendUser(ApplyRecord ar, List<String> userList, String corpId, String token) {
    	if(ar != null && CollectionUtils.isNotEmpty(userList)) {
    		String userIds = "";
    		for(String userId : userList) {
    			userIds += userId + ",";
    		}
    		if(userIds.length() > 0) userIds = userIds.substring(0, userIds.length() - 1);
    		List<MeetingScope> list = new ArrayList<MeetingScope>();
    		List<Map<String,Object>> users = userApiService.getUserList(userIds, corpId, "", token);
    		MeetingScope attendMS = null;
    		for(Map<String,Object> user : users) {
    			attendMS = new MeetingScope();
    			attendMS.setScopetype("user");
    	        attendMS.setType("ID");
    	        attendMS.setScopevalue(StringUtils.null2String(user.get("id")));
    	        attendMS.setName(StringUtils.null2String(user.get("userName")));
    	        attendMS.setFielddatatable("oa_meeting_apply_record");
    			attendMS.setFielddatavalue(ar.getAttendUser());
    	        attendMS.setFielddata("attend_user");
    	        attendMS.setDeleteflag("0");
    	        attendMS.setSortNo(0);
    	        list.add(attendMS);
    		}
    		meetingScopeService.save(list);
    	}
    }
    
    public int updateIsCycle(String cycleId) {
    	return this.dao.updateIsCycle(cycleId);
    }
    
    /**
     * 会议室变更
     * @param newEntity
     * @param oldEntity
     */
    public void changeBoardroom(ApplyRecord newEntity, ApplyRecord oldEntity, String deleteId) {
    	String newdBoardroomId = newEntity.getBoardroomId();
    	String oldBoardroomId = oldEntity.getBoardroomId();
    	//已预定会议室改为自定义会议地点，已预定会议室释放
    	if(StringUtils.isNotBlank(oldBoardroomId) && StringUtils.isBlank(newdBoardroomId)) {
    		ApplyRecord entity = new ApplyRecord();
    		entity.setBoardroomId(oldBoardroomId);
    		entity.setStartTime(oldEntity.getStartTime());
    		entity.setEndTime(oldEntity.getEndTime());
    		entity.setStatus(1);
    		entity.setMeetingServe(oldEntity.getMeetingServe());
    		//已预定会议室释放
    		super.save(entity);
    	}
    	//自定义会议地点改为已预定会议室
    	else if(StringUtils.isNotBlank(newdBoardroomId) && StringUtils.isBlank(oldBoardroomId)) {
    		super.delete(this.findOne(deleteId));
    	}
    	//已预定会议室变更，原已预定会议室释放
    	else if(!StringUtils.equals(newdBoardroomId, oldBoardroomId)) {
    		ApplyRecord entity = new ApplyRecord();
    		entity.setBoardroomId(oldBoardroomId);
    		entity.setStartTime(oldEntity.getStartTime());
    		entity.setEndTime(oldEntity.getEndTime());
    		entity.setStatus(1);
    		entity.setMeetingServe(oldEntity.getMeetingServe());
    		//原已预定会议室释放
    		super.save(entity);
    		super.delete(this.findOne(deleteId));
    	}
    }
}